#include #include #include //for class string using namespace std; /* Loop right to left through the characters of the string with a "reverse iterator" it. Use the funcions begin and end for a plain old iterator, Use the funcions rbegin and rend for a reverse iterator. */ int main() { cout << "Please input an integer in binary: "; string s; cin >> s; if (!cin) { cerr << "Sorry, I couldn't receive that.\n"; return EXIT_FAILURE; } int power {1}; //Run through the powers of 2: 1, 2, 4, 8, 16, 32, etc. int sum {0}; for (auto it {rbegin(s)}; it != rend(s); ++it) { if (*it == '1') { // *it is each character of the string sum += power; } else if (*it != '0') { cerr << "Bad character '" << *it << "' in string.\n"; return EXIT_FAILURE; } power *= 2; //means power = power * 2; } cout << "binary " << s << " = decimal " << sum << "\n"; return EXIT_SUCCESS; }