我最近买了C++ Primer并遇到了问题。我必须使用cin
阅读一系列单词并将值存储在vector
中。遇到异常问题后,我发现while(cin >> words)
如果您期望无效输入,则会引发问题(如无限循环):Using cin to get user input
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;
}
因此,我正试图找到这个问题的替代方案。帮忙?
答案 0 :(得分:3)
您提供的有关输入问题的链接略有不同。它是在谈论您希望用户输入特定值时,但您可能无法读取该值(假设它是一个整数),因为输入了其他内容。在这种情况下,最好使用getline
检索整行输入,然后解析该值。
在你的情况下,你只是在言语之后。当您从流中读取字符串时,它将为您提供所有连续的非空白字符。并且,暂时忽略标点符号,您可以将其称为“单词”。所以当你谈到'无效输入'时,我看不出你的意思。循环将继续为您提供“单词”,直到流中没有任何内容为止,此时它将出错:
vector<string> words;
string word;
while( cin >> word ) words.push_back(word);
但是,如果您希望用户在一行中输入所有单词并按Enter键完成,则需要使用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);
}