#include #include //for the standard library "string to integer" function stoi #include using namespace std; int main() { for (;;) { cout << "Input an integer in binary (or control-d to end): "; string s; cin >> s; //Attempt to input a string. if (!cin) { //If attempt was unsuccessful (i.e., control-d) break; //out of the loop } try { const int i {stoi(s, nullptr, 2)}; cout << "Binary " << s << " is decimal " << i << "\n\n"; } catch (invalid_argument e) { //Arrive here if user typed characters other than 1 or 0 cerr << "Sorry, in binary you can type " << " only 1s and 0s.\n" << "Try again.\n"; } catch (out_of_range e) { //Arrive here if user typed binary number that's too big cerr << "Sorry, the biggest binary number " << "that will fit in an int on our machine is\n" << "1111111111111111111111111111111\n" << "(with thirty-one 1s).\n" << "Try again.\n"; } } cout << "\n"; //Arrive here when user typed control-d return EXIT_SUCCESS; }