cin输入停止窗口关闭被忽略

时间:2019-05-05 18:47:27

标签: c++

我正在尝试编写一段使某些单词“瘫痪”的代码。我已经做到了,但是当试图停止关闭窗口的操作时,我的cin被忽略了。我正在使用“编程:使用C ++的原理和实践”作为指南。

我的代码:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;


int main()
{
vector <string> words;
vector <string> bad_words = {"bad", "heck"};

cout << "When you are finished entering words press enter then Control Z." << '\n';
for (string single_word; cin >> single_word;) // read white space seperated words
   words.push_back(single_word); // puts it in the vector 

for (int i = 0; i < words.size(); ++i) {
    if (find(bad_words.begin(), bad_words.end(), words[i]) 
    != bad_words.end()) //reads through the vector searching for word i
        cout << "BLEEP!" << '\n';
    else {
        cout << words[i] << '\n';
    }
}
char stop;
cin >> stop;
}

展开:从Visual Studio执行程序或通过手动单击执行程序时,该键不起作用。

1 个答案:

答案 0 :(得分:0)

operator>>忽略前导空格,其中包括换行符。因此,在键入 CTRL-Z 之前,您的读取循环不会结束,然后在程序末尾读取char的后续尝试将不会读取任何内容。

您应该改为使用std::getline()来读取用户的输入,直到换行符为止,然后可以使用std::istringstream来读取读取的输入中的单词,例如:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

int main()
{
    vector<string> words;
    vector<string> bad_words = {"bad", "heck"};
    string line;

    cout << "When you are finished entering words press enter then Control Z." << '\n';

    getline(cin, line);
    istringstream iss(line); 

    for (string single_word; iss >> single_word;) // read white space seperated words
        words.push_back(single_word); // puts it in the vector

    for (int i = 0; i < words.size(); ++i)
    {
        if (find(bad_words.begin(), bad_words.end(), words[i]) != bad_words.end()) //reads through the vector searching for word i
            cout << "BLEEP!" << '\n';
        else
            cout << words[i] << '\n';
    }

    char stop;
    cin >> stop;

    return 0;
}