读取单词序列以将它们添加到向量中 [英] Reading a sequence of words to add them in a vector
问题描述
我最近购买了 C ++ Primer 和卡住了一个问题.我必须使用 cin
读取单词序列,并将值存储在 vector
中.在遇到异常问题之后,我发现 while(cin>>单词)
会引发问题(例如无限循环),如果您期望输入无效:
I recently bought a C++ Primer and got stuck with a problem. I have to read a sequence of words using cin
and store the values in a vector
. After having unusual problems, I found out that while(cin >> words)
invites problems (like infinite loop) if you expect invalid inputs: 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;
}
因此,我正在尝试找到此问题的替代方法.帮助吗?
Therefore, I'm trying to find an alternative to this problem. Help ?
推荐答案
您提供的有关输入问题的链接有些不同.它是在讨论您期望用户何时输入特定值,但是由于输入了其他内容,您可能无法读取该值(假设它是整数).在这种情况下,最好使用 getline
检索整行输入,然后将值解析出来.
That link you provided regarding input problems is a little different. It's talking about when you expect the user to enter a particular value, but you might fail to read the value (let's say it's an integer) because something else was entered. In that case, it's good to use getline
to retrieve a whole line of input and then parse the value out.
就您而言,您只是在说话.从流中读取字符串时,它将为您提供所有连续的非空白字符.而且,暂时忽略标点符号,可以将其称为单词".因此,当您谈论无效输入"时,我看不到您的意思.循环将继续为您提供单词",直到流中没有剩余的单词,这时它将出错:
In your case, you're just after words. When you read a string from a stream, it will give you all consecutive non-whitespace characters. And, ignoring punctuation for a moment, you can call that a "word". So when you talk about 'invalid input', I don't see what you mean. The loop will continue to give you "words" until there are none left in the stream, at which point it will error:
vector<string> words;
string word;
while( cin >> word ) words.push_back(word);
但是,如果您希望用户在一行上输入所有单词并按Enter键完成操作,那么您需要使用getline:
However, if you expect the user to enter all words on one line and press enter to finish, then you need to use 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);
}
这篇关于读取单词序列以将它们添加到向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!