首页 > 为什么eof ctrl+d模拟工作不正常?

为什么eof ctrl+d模拟工作不正常?

下面一段C++测试代码,while loop使用eof来跳出循环。

string s1;
while (cin >> s1)
{
    cout << s1 << endl;
}
// cout << cin << cin << cin << endl; //加入输出 000
// cin.ignore(10000,'0'); //加入无效
// cin.clear() // 加入无效

string s3, s4;
cout << "input two strings: " << endl;
getline(cin, s3);
getline(cin, s4);
if (s3 == s4){
    cout << "the strings are equal!" << endl;
}
else if (s3 > s4) {
    cout << "s3 is larger!" << endl;
} else {
    cout << "s4 is larger!" << endl;
}

在mac终端运行结果如下,粗体为我的输入,斜体为cout打印。
可以看到要求输入两string的时候压根就没有输入机会就玩儿蛋了。
hello world
hello
world
input two strings:
the strings are equal!

另外加入注释代码也不能让cin 重新工作。
如果注释貂s1 相关循环代码,s3 s4测试代码可以真常工作。

请问这是为什么?mac 终端 ctrl+d 模拟eof 之后需要做什么特殊设置才能工作吗?谢谢。


自己测试 我到原因了。
因为EOF一直都在cin stream里面,clear()之后每次cin 读入都是读入EOF,自然统统出错。
google 了很久都没有找到flush terminal EOF 的方法。有没有建议怎么flush terminal EOF?还是C++根本就没有这个选项,需要继续测试只能另开一个工程?谢谢!

update:
找到方法了。结合下面两个函数就可以flush eof,然后继续接受输入。
cin.clear();
clearerr(stdin); // combine with cin.clear() and clearerr(stdin) works!


在win下 使用MSYS32上测试没有问题
代码跟你一样
使用cin.clear();
而且官方istream::clear的相关说明有讲到可以设置eofbit为false

【热门文章】
【热门文章】