问题
I am wondering why does the following code not work as expected:
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
string s;
//scanf("%d",&n);
cin >> n;
ios_base::sync_with_stdio(false);
cin >> s;
cout << n << " " << s;
return 0;
}
Input:
10
abcd
Output: 10
The string is not getting printed! The result is same if I use scanf
to input the integer. However, the code does work as expected if the line ios_base::sync_with_stdio(false);
is placed before the first cin
(or before the scanf
) instead.
I would highly appreciate any help to clarify this behaviour.
Edit:
The inputs are contained in a file inp.txt
and I am using <
(re-direction operator) to read from the file and >
to output the result to out.txt
, like:
a.out < inp.txt > out.txt
The code gives expected output if the inputs are given directly from console. Sorry for any misunderstanding or confusion.
回答1:
Calling sync_with_stdio after I/O has been performed leads to implementation-defined behavior (which is stronger wording than cppreference's "has any effect"):
Effects: If any input or output operation has occurred using the standard streams prior to the call, the effect is implementation-defined. Otherwise, called with a false argument, it allows the standard streams to operate independently of the standard C streams.
In libc++, nothing happens because all it does is toggle a flag. In libstdc++, it actually performs logic to switch the streams. Any further attempt to use the streams results in failure:
cin >> s;
cin.clear();
cin >> s;
std::cout << n << " " << s;
Either way, the libstdc++ manual states you need to call the function before performing I/O. So what you actually have is undefined behavior now.
来源:https://stackoverflow.com/questions/37468606/ios-basesync-with-stdiofalse-does-not-work-between-two-inputs-from-stdin