Reading a sequence of words to add them in a vector

喜夏-厌秋 提交于 2020-12-06 04:01:49

问题


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 ?


回答1:


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);

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);

Or you can do this:

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);
}


来源:https://stackoverflow.com/questions/14347033/reading-a-sequence-of-words-to-add-them-in-a-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!