+ 1
[Solved] Help me!!!! How c++ handles variables during input failures.
Fail states
20 Antworten
+ 2
Great after a long search, I had to change my query style and I found the solution. It is something that has to do with c++ version development and this link will explain it all. And don't worry as you wouldn't be bored.
http://www.cplusplus.com/forum/beginner/144062/
+ 3
try something like this, notice the temp variable.
int num;
int temp;
while(cin.good()){
temp = num;
cin >> num;
}
cin.clear();
cout << "last entry was " << temp;
+ 2
Hello, everyone, I have got a question. During data entry via cin, memory called a buffer holds these entries until extracted into variables.
Suppose I have got a single variable and given this code bit;
int num;
cin >> num;
while (cin)
{
cin >> num;
}
cout << num;
And my entries are 1, 2, f
At the end of program execution, num = 0.
But my expectation is after input stream enters a fail state, num = 2.
So what happened????
+ 1
I am trying to understand what happens during input
+ 1
So why does it do that??
+ 1
You aren't getting me.
The code isn't a sort of task I want to do hence experiencing a problem. I just am experimenting with the behaviors of certain token, functions, etc.
So I need explanation to the behaviour I see.
+ 1
From what I got from a telegram group, the answerer supposes that since the invalid data could not be extracted into the num variable, cin might have just set the variable to a default value. And that kinda sounds like the case except I don't know.
However, using codeblocks as my ide, I have noticed that uninitiated int variables have 0 as default value.
Maybe my source might be right.
0
Well, the code is to have user continuously enter any number until input is invalid.
0
If I make it not cin, then the loop will be infinite
0
The whole thing is that I thought an invalid input causing a fail state would just ignore other entries within that current input stream. But here as I am using the same variable all the time, it appears as that variable simply reset itself even though it previously had a matching entry
0
The only way I can explain it is (not sure if it's technically correct)...
It's the invalid entry that causing the cin to fail, but it's still extracted into the variable.
I'll be watching this thread to see how C++ experts explain it.
0
Tell me how can i help you???
0
Well, you see my code, I gave 3 input, with the last one meant to create an input failure hence end the loop. I expected that the second input should remain assigned to the variable after the next invalid input but it just wasn't so. Instead the variable num was assigned zero. I would be very glad if anyone can give the "theoretical" explanation to that.