今天使用C++编写了一段小程序,练习使用标准库的算法,代码如下:
1 #include2 #include 3 #include 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 #include2 #include 3 #include 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 }
运行结果如下所示: