Search code examples
c++foreachdynamic-arrays

c++ parse getline in dynamic array


I already asked, how I can parse single words from a stream into variables, and that works perfectly, but I don't know how many words the user will give as input. I thought I could parse it into a dynamic array, but I don't know where to start. How can I write "for each word in line"?

This is how I parse the words into the vars:

string line;
getline( cin, line );
istringstream parse( line );
string first, second, third;
parse >> first >> second >> third;

Thanks!

EDIT: Thanks to all of you, I think I get it know... and it works!


Solution

  • You could use std::vector<std::string> or std::list<std::string> -- they handle the resizing automatically.

    istringstream parse( line ); 
    vector<string> v;
    string data; 
    while (parse >> data) {
      v.push_back(data);
    }