您提供的有关输入问题的链接有些不同。它指的是您何时期望用户输入特定值,但您可能无法读取该值(假设它是一个整数),因为输入了其他内容。在这种情况下,最好使用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);
}