The basic idea of my code is for the user to enter either the spelling of 0-9 i.e. zero, one etc. or the actual numeral and for it to output the numeral/spelling respectively.
I managed to do this with a while loop using while(cin >> number) (number being a string variable) and then use if statements to select the appropriate output option i.e. “zero” –> 0, and “0”–> zero.
At first though I tried to do it as follows;
while (cin >> number || cin >> n)
{
if (n == 0)
cout << digits[0] << endl;
.
.
.
else if (n == 9)
cout << digits[9] << endl;
if (number == digits[0])
cout << 0 << endl;
.
.
.
else if (number == digits[9])
cout << 9 << endl;
}
digits is just a vector class that stores the strings “zero”, “one” etc.
This didn’t work though, when a string was entered the output was correct but when an integer was entered the output was always “zero”. I was wondering why this doesn’t work? I figured its something to do with the while loop conditions. Can’t the computer identify if a string/integer was entered and carry out the appropriate action?
The problem is that
cin >> numberis always going to succeed sincenumberis astring(as long as you don’t hit EOF or some other failure condition); if the user types in a digit,numberis going to hold the number as a string. Socin >> nwon’t happen.You should compare your
numberagainst the strings"0".."9"instead (in addition to testing the digit names). You should also use a loop instead of a chain ofif/else if.