I have been making simple programs to solidify my basic knowledge of C++. But while making this Binary converter I came across a problem.
I cant seem to figure out how to ignore input after 8 characters. I want to read in the first 8 characters the user inputs and discard the rest.
If cin.ignore is an option I cant figure out how to do it.
Code:#include <iostream> int BinToDec ( char *bits ) { int result = 0; int mask = 1; for ( int loop = 7; loop >= 0; loop -- ) { if ( bits [loop] != '0' && bits [loop] != '1' ) { std::cout << "Error: Invalid Input\n"; return -1; } else if ( bits [loop] == '1' ) result += mask; mask *= 2; } std::cout << "\nResults:\n"; std::cout << "Bin: " << bits << '\n'; std::cout << "Dec: " << result << '\n'; std::cout << "Ascii: " << static_cast <char> ( result ) << '\n'; return 0; } int main () { char bit_array [8]; memset ( bit_array, 0, 8); std::cout << "You must enter 8 bits. Q to exit\n\n"; while ( 1 ) { std::cout << "\nEnter a binary value: "; std::cin >> bit_array; if ( bit_array[0] == 'q' ) break; BinToDec ( bit_array ); } std::cout << "\nGoodbye.\n"; return 0; }![]()



LinkBack URL
About LinkBacks



