c++ - 为什么eof ctrl+d模拟工作不正常?
大家讲道理
大家讲道理 2017-04-17 11:41:31
[C++讨论组]

下面一段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 之后需要做什么特殊设置才能工作吗?谢谢。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
阿神

自己测试 我到原因了。
因为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!

PHPz

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号