#include #include #include //for class string using namespace std; /* Loop from right to left through the characters of the string. The string contains s.size() characters. The rightmost character is at subscript s.size() - 1. The leftmost character is at subscript 0. */ 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}; //Runs through the powers of 2: 1, 2, 4, 8, 16, 32, etc. int sum {0}; for (int i = s.size() - 1; i >= 0; --i) { if (s[i] == '1') { //s[i] is each character of the string s sum += power; } else if (s[i] != '0') { cerr << "Bad character '" << s[i] << "' in string.\n"; return EXIT_FAILURE; } power *= 2; //means power = power * 2; } cout << "binary " << s << " = decimal " << sum << "\n"; return EXIT_SUCCESS; }