我最近买了一个C++ 入门 https://rads.stackoverflow.com/amzn/click/com/0321714113并遇到了一个问题。我必须使用以下方式读取单词序列cin
并将值存储在vector
。在遇到不寻常的问题后,我发现while(cin >> words)
如果您期望输入无效,则会引发问题(例如无限循环):使用 cin 获取用户输入 http://www.cplusplus.com/forum/articles/6046/
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;
}
因此,我正在尝试寻找解决这个问题的方法。帮助 ?
您提供的有关输入问题的链接有点不同。它谈论的是当您期望用户输入特定值,但您可能无法读取该值(假设它是一个整数),因为输入了其他内容。在这种情况下,最好使用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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)