ios_base::sync_with_stdio(false) does not work between two inputs from stdin

喜欢而已 提交于 2020-01-17 05:23:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!