ios_base :: sync_with_stdio(false)在来自stdin的两个输入之间不起作用 [英] ios_base::sync_with_stdio(false) does not work between two inputs from stdin
问题描述
我想知道为什么以下代码无法按预期工作:
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;
}
输入:
10
abcd
输出: 10
字符串未打印!如果使用 scanf
输入整数,则结果相同。但是,如果将行 ios_base :: sync_with_stdio(false);
放在第一个 cin
(或者在 scanf
之前)。
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.
编辑:
输入包含在文件 inp.txt
中,我正在使用<
(重定向运算符)从文件中读取,并使用>
将结果输出到 out.txt
,例如:
a.out< inp.txt> out.txt
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.
推荐答案
调用 sync_with_stdio
执行完I / O导致实施定义的行为(比cppreference的有任何效果更强的措词):
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"):
效果:在调用之前使用标准流进行了输入或输出操作,效果是实现定义的
。否则,使用错误的参数调用它,它
允许标准流独立于标准C
流运行。
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 ++中,它实际上执行逻辑来切换流。使用该流的任何进一步尝试都会导致失败:
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;
无论哪种方式, libstdc ++手册指出,您需要在执行I / O之前调用函数 。因此,您现在实际拥有的是未定义的行为。
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.
这篇关于ios_base :: sync_with_stdio(false)在来自stdin的两个输入之间不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!