C++中标准输入流cin与Ctrl+Z使用时的问题

本文介绍了一个使用C++标准库算法的小程序,在输入字符串后查找特定关键字的位置。文章详细解释了当用户使用Ctrl+Z结束输入时,如何解决输入流状态导致的关键字无法读取的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天使用C++编写了一段小程序,练习使用标准库的算法,代码如下:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 #include <string>
 5 
 6 using std::vector;
 7 using std::cin;
 8 using std::cout;
 9 using std::endl;
10 using std::string;
11 
12 int main() {
13     vector<string> vec;
14     string str;
15     cout << "Please enter some string..." << endl;
16     while (cin >> str) {
17         vec.push_back(str);
18     }
19     cout << "Please enter the key word: ";
20     cin >> str;
21     auto result = find(vec.cbegin(), vec.cend(), str);
22     if (result == vec.cend()) {
23         cout << "Failed to find the key word..." << endl;
24     } else {
25         cout << "Succeed to find the key word, it is the " << result - vec.cbegin() + 1 << "th word..." << endl;
26     }
27     system("pause");
28     return 0;
29 }

然而运行时却出现了问题,运行截图如下:

从运行结果来看,第20行的cin >> str;根本没有执行,于是输出cin的状态位看看出了什么问题:

1 cout << "cin.fail() = " << cin.fail() << endl;
2 cout << "cin.bad() = " << cin.bad() << endl;
3 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的所有条件状态位复位,将状态设置为有效即可。

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 #include <string>
 5 
 6 using std::vector;
 7 using std::cin;
 8 using std::cout;
 9 using std::endl;
10 using std::string;
11 
12 int main() {
13     vector<string> vec;
14     string str;
15     cout << "Please enter some string..." << endl;
16     while (cin >> str) {
17         vec.push_back(str);
18         cout << "Push str = " << str << endl;
19     }
20     cout << "Please enter the key word: ";
21     cin.clear();
22     cin >> str;
23     cout << "str = " << str << endl;
24     cout << "cin.fail() = " << cin.fail() << endl;
25     cout << "cin.bad() = " << cin.bad() << endl;
26     cout << "cin.eof() = " << cin.eof() << endl;
27     auto result = find(vec.cbegin(), vec.cend(), str);
28     if (result == vec.cend()) {
29         cout << "Failed to find the key word..." << endl;
30     }
31     else {
32         cout << "Succeed to find the key word, it is the " << result - vec.cbegin() + 1 << "th word..." << endl;
33     }
34     system("pause");
35     return 0;
36 }

运行结果如下所示:

转载于:https://www.cnblogs.com/jzincnblogs/p/4994956.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值