今天使用C++编写了一段小程序,练习使用标准库的算法,代码如下:
#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() + << "th word..." << endl;
}
system("pause");
return ;
}
然而运行时却出现了问题,运行截图如下:
从运行结果来看,第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() + << "th word..." << endl;
}
system("pause");
return ;
}
运行结果如下所示: