Oops. I didn't mean to put the cin right before the while (nextDigit!='\n')
It is not required.
Let's go through the logic.
So let's say I type in 9393
The buffer gets '9' '3' '9' '3' '\n'
So we get into the while loop and so far '9' has been read in. We still have '3' '9' '3' '\n' to go through
in our while loop we check if the current digit is the newline ('\n')
If it is not the newline, we get the next character '3'
We still have '9' '3' and '\n' in the buffer
The while loop keeps going
we get '9' we still have '3' and '\n' in the buffer
we get the '3' and all that is left in the buffer is '\n'
So we call that cin >> nextDigit and now nextDigit = '\n' so our while loop ends
The last cin call is just to get the next input for the next number the user tries to type in.
But yeah, the first cin is not required and it can be removed so the code would be
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
using namespace std;
int main() {
char nextDigit;
long int decimalValue = 0;
cin.unsetf(ios_base::skipws);
cin >> nextDigit;
bool ValidInput = false;
while (ValidInput == false)
{
while (nextDigit != '\n') {
if (nextDigit != '0' && nextDigit != '1') //If character is not 0 && not 1
{
cout << "Invalid Binary Entry. Try again." << endl;
ValidInput = false;
while (nextDigit != '\n')
{
cin >> nextDigit;
}
cin >> nextDigit;
break;
}
ValidInput = true;
decimalValue = ((decimalValue * 2) + nextDigit - 48);
cin >> nextDigit;
}
}
cout << "Decimal value is: " << decimalValue << endl;
return 0;
}
|