Hey guys, so I was trying to create a calculator that lets you use strings up to ten, and numbers. The program creates a vector of strings "zero" to "ten", then it creates a value as so
1 2 3 4 5 6
int val1 = getinput();
..
char op;
cin>>op
..
int val2 = getinput();
The getinput() function looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13
constint not_a_symbol = numbers.size();// not_a_symbol is a value that does //not correspond
// to a string in the numbers vector
int val = not_a_symbol;
if (cin>>val) return val; // try to read an integer composed of digits
cin.clear(); // clear string after failed attempt to read an integer
string s;
cin>>s;
for (int i=0; i<numbers.size(); ++i) // see if the string is in numbers
if (numbers[i]==s) val = i;
if (val==not_a_symbol) error("unexpected number string: ",s);
return val;{
I understand how its working, its asking for an integer, then returning it, but its its not an int than it gets a string and checks if that string is in the vector using a for loop. I don't understand how its able to do a double check on the input using cin without asking to reenter input after a failed attempt to read an integer. I know it clears cin so we can get more input but I dont know why its able to take the input we gave it in our first cin to our second cin (string), sorry if this makes no sens.e
When an error occurs the stream position is not changed. Just the error is set. Hence after clearing the error you can continue reading from that unchanged position.
Yea I know It cleans cin's errors is what I meant, this doesn't really answer my question at all but its okay I figured it out. My Question was what is happening with the lingering first input that fails, and I figured it out myself thanks :)
That's not at all what you said. You said "I know it clears cin so we can get more input ... I don't understand how its able to do a double check on the input using cin without asking to reenter input after a failed attempt to read an integer". So you were obviously thinking that it would clear the input buffer. But in fact it only "clears" the error state of the stream. The string remains behind since it was unable to be read. There is, in fact, no way to "clear" the input buffer except by reading it (perhaps with ignore).
haha, jeez man calm down, I know thats not what I said and thats why I corrected myself the second time by saying I meant to say it clears error so we can continue with input, but yea after a small search online I figured it out :)