C++中标准输入流cin与Ctrl+Z使用时的问题
2015-11-25 16:00
507 查看
今天使用C++编写了一段小程序,练习使用标准库的算法,代码如下:
然而运行时却出现了问题,运行截图如下:
从运行结果来看,第20行的cin >> str;根本没有执行,于是输出cin的状态位看看出了什么问题:
可以看出,输入流cin的failbit以及eofbit已经被置位,但badbit没有置位,这说明cin流并没有崩溃,但是流已经到达了文件结束,IO操作失败,因此cin >> str;自然没有成功执行。
而问题出现的原因在于while(cin>>str)语句在结束输入时使用了Ctrl+Z,告诉cin用户已经结束了输入,所以eofbit与failbit被置位。
为了让程序正常运行,只需调用cin.clear()让cin的所有条件状态位复位,将状态设置为有效即可。
运行结果如下所示:
#include <iostream> #include <algorithm> #include <vector> #include <string> using std::vector; using std::cin; using std::cout; using std::endl; using std::string; int main() { vector<string> vec; string str; cout << "Please enter some string..." << endl; while (cin >> str) { vec.push_back(str); } cout << "Please enter the key word: "; cin >> str; auto result = find(vec.cbegin(), vec.cend(), str); if (result == vec.cend()) { cout << "Failed to find the key word..." << endl; } else { cout << "Succeed to find the key word, it is the " << result - vec.cbegin() + 1 << "th word..." << endl; } system("pause"); return 0; }
然而运行时却出现了问题,运行截图如下:
从运行结果来看,第20行的cin >> str;根本没有执行,于是输出cin的状态位看看出了什么问题:
cout << "cin.fail() = " << cin.fail() << endl; cout << "cin.bad() = " << cin.bad() << endl; cout << "cin.eof() = " << cin.eof() << endl;
可以看出,输入流cin的failbit以及eofbit已经被置位,但badbit没有置位,这说明cin流并没有崩溃,但是流已经到达了文件结束,IO操作失败,因此cin >> str;自然没有成功执行。
而问题出现的原因在于while(cin>>str)语句在结束输入时使用了Ctrl+Z,告诉cin用户已经结束了输入,所以eofbit与failbit被置位。
为了让程序正常运行,只需调用cin.clear()让cin的所有条件状态位复位,将状态设置为有效即可。
#include <iostream> #include <algorithm> #include <vector> #include <string> using std::vector; using std::cin; using std::cout; using std::endl; using std::string; int main() { vector<string> vec; string str; cout << "Please enter some string..." << endl; while (cin >> str) { vec.push_back(str); cout << "Push str = " << str << endl; } cout << "Please enter the key word: "; cin.clear(); cin >> str; cout << "str = " << str << endl; cout << "cin.fail() = " << cin.fail() << endl; cout << "cin.bad() = " << cin.bad() << endl; cout << "cin.eof() = " << cin.eof() << endl; auto result = find(vec.cbegin(), vec.cend(), str); if (result == vec.cend()) { cout << "Failed to find the key word..." << endl; } else { cout << "Succeed to find the key word, it is the " << result - vec.cbegin() + 1 << "th word..." << endl; } system("pause"); return 0; }
运行结果如下所示:
相关文章推荐
- C语言实现1000--2000的闰年判断
- C++primer plus第六版课后编程练习答案4.6
- C++primer plus第六版课后编程练习答案4.5
- C++内存管理
- C++primer plus第六版课后编程练习答案4.4
- 传智播客C++进驻广州羊城
- C++primer plus第六版课后编程练习答案4.3
- c++实现读取配置文件
- C++确定常量的数据类型
- C++primer plus第六版课后编程练习答案4.2
- php调用一个c语言写的接口问题
- C++之处理snmp请求的代理模型类
- C++中的头文件和源文件:如何写头文件
- C++ class constructor and destructor
- C++之自己封装socket操作的业务类
- C++之字符串常用操作类集合
- C++结构体对齐
- c语言返回栈内存的问题
- c++ ftream
- C++ virtual关键字