我想知道为什么下面的代码没有按预期工作:
#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;
}
输入:
10
abcd
输出:10
字符串没有被打印出来!如果我使用 scanf
结果是一样的输入整数。但是,如果 ios_base::sync_with_stdio(false);
行,代码确实会按预期工作。放在第一个 cin
之前(或在 scanf
之前)代替。
如果您能帮助澄清此行为,我将不胜感激。
编辑:
输入包含在文件 inp.txt
中我正在使用 <
(重定向运算符)从文件中读取和 >
将结果输出到out.txt
, 喜欢:
a.out < inp.txt > out.txt
如果输入是直接从控制台给出的,代码会给出预期的输出。对于任何误解或混淆,我们深表歉意。
最佳答案
调用 sync_with_stdio
在 I/O 执行后导致实现定义的行为(这比 cppreference 的“有任何影响”的措辞更强):
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.
在 libc++ 中,什么也不会发生,因为它所做的只是切换一个标志。在 libstdc++ 中,它实际上执行 logic切换流。任何进一步尝试使用流都会导致失败:
cin >> s;
cin.clear();
cin >> s;
std::cout << n << " " << s;
无论哪种方式,the libstdc++ manual声明您需要在 执行 I/O 之前调用函数。所以你现在实际拥有的是未定义的行为。
关于c++ - ios_base::sync_with_stdio(false) 在来自标准输入的两个输入之间不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37468606/