Given this code:
#include <cstdio>
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::string;
int main() {
int a;
string b;
cin >> a;
cin >> b;
return 0;
}
I tried compiling it with g++ and running it.
When assigning a char to a, at the first cin, the following instruction seems to be skipped.
Even if add two getchar() instructions between the last two lines, only the second getchar() seems to be executed.
Can somebody accurately explain what’s happening at low level, which seemingly results in an apparent non execution of those lines?
EDIT:
Using this debug code:
#include <cstdio>
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
int a;
string b;
cin >> a;
cin >> b;
cout << "a is "<< a << endl;
cout << "b is "<< b << endl;
getchar();
return 0;
}
INPUT
1test
OUTPUT
a is 1
b is test
* No getchar executed *
INPUT
1
test
OUTPUT
a is 1
b is test
INPUT
ttest
OUTPUT
a is 0
b is
INPUT
t
// Skips the second cin
OUTPUT
a is 0
b is
NOTE:
getchar() was not executed even once.
Two things, judging from your output. The first is when you enter
"ttest", thecin >> a;fails. This putscinin an error state,where it will remain until the error is cleared. And as long as it is
in an error state, all other operations are no-ops. You really need to
test the results of the input before trying to use the values:
(And don’t use a non-initialized variable, like
a, until it has beensuccessfully input.)
The second is that the
>>operator only extracts the charactersnecessary for its target:
>>to anintwill stop at the firstnon-numeric character, and
>>to astd::stringat the first whitespace (in both cases, after having skipped leading white space). This
means that after something like
"1test\n", there will still be a'\n'in the buffer. And while it’s generally a bad idea to mixFILE*(likegetchar()) and iostream, if they’re correctlysynchronized,
getchar()will read this'\n'immediately and return.If you’re reading line oriented input, the best solution is to use
getline(), and then put the line into astd::istringstreamto parseit. So your code might end up looking like: