#include #include using namespace std; const char* BINARY_DIGITS = "01"; int bin2int(const char* txt); int binaryDigitValue(char digit); // Return 0, 1, or -1 for // non-binary digit int main() { char txt[64]; while (true) { cout << "Enter a binary representation of an integer number" " (q for the end):" << endl; if (!(cin.getline(txt, 62)) || txt[0] == 'q') break; int n = bin2int(txt); cout << "Integer: " << n << endl; } return 0; } int bin2int(const char* txt) { int s = 1; // Sign of a number if (*txt == '-') { s = (-1); ++txt; } int n = 0; while (*txt != 0) { int d = binaryDigitValue(*txt); if (d < 0) break; n = n*2 + d; ++txt; } return s*n; } int binaryDigitValue(char digit) { int d = 0; while (d < 2) { if (digit == BINARY_DIGITS[d]) return d; ++d; } return (-1); // This is not a binary digit }