读取一系列单词并将它们添加到向量中

3

我最近购买了一本C++ Primer,但遇到了一个问题。我需要使用cin读取一系列单词,并将其存储在vector中。在遇到异常问题后,我发现如果你期望输入无效的数据,while(cin >> words)会引发问题(例如无限循环):使用cin获取用户输入

int main()
{
    string words;
    vector<string> v;
    cout << "Enter words" << endl;
    while (cin >> words)
    {
        v.push_back(words);
    }
    for(auto b : v)
        cout << b << "  ";
    cout << endl;
    return 0;
}

因此,我试图寻找这个问题的替代方案。有帮助吗?

2
如果你不预料到无效的输入,那么你就过于乐观了。 - jrok
2
不,它不会。它会停止循环。如果这个特定条件导致了无限循环,那么你做错了其他事情。 - jrok
1
@AyushAgarwal,只需进行最少的修改即可使其正常运行:http://liveworkspace.org/code/kzsl0%241。什么被视为无效? - chris
3
用户输入的“整数”是一个字符串。如果你想确定什么是单词,什么不是单词,那么你必须检查每个输入的字符串中的字符,并决定是否将其放入你的向量中。 - paddy
2
哦,我明白了。嗯,在字符串方面,实际上并不存在无效输入。他们可能指的是如果流结束(例如文件末尾或其他错误),但因为你正在从cin输入,所以没有文件末尾(在Linux中,你可以通过按Ctrl-D来使cin结束)。 - paddy
显示剩余13条评论
1个回答

4
您提供的关于输入问题的链接略有不同。它是指当您期望用户输入特定值时,但可能由于输入其他内容(比如整数)而无法读取该值。在这种情况下,最好使用getline来检索整行输入,然后解析出该值。
在您的情况下,您只需要单词。当您从流中读取字符串时,它将为您提供所有连续的非空白字符。而且,暂时忽略标点符号,您可以称之为“单词”。所以当您谈论“无效输入”时,我不明白您的意思。循环将继续向您提供“单词”,直到流中没有剩余的“单词”,此时它将报错:
vector<string> words;
string word;
while( cin >> word ) words.push_back(word);

然而,如果您期望用户在一行上输入所有单词并按回车键完成,则需要使用getline函数:

// Get all words on one line
cout << "Enter words: " << flush;
string allwords;
getline( cin, allwords );

// Parse words into a vector
vector<string> words;
string word;
istringstream iss(allwords);
while( iss >> word ) words.push_back(word);

或者您可以这样做:
cout << "Enter words, one per line (leave an empty line when done)\n";

vector<string> words;
string line;
while( getline(cin, line) )
{
    // Because of the word check that follows, you don't really need this...
    if( line.size() == 0 ) break;

    // Make sure it's actually a word.
    istringstream iss(line);
    string word;
    if( !(iss >> word) ) break;

    // If you want, you can check the characters and complain about non-alphabet
    // characters here...  But that's up to you.

    // Add word to vector
    words.push_back(word);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接