Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 802
mohrphium Avatar asked Jul 30 '26 17:07

mohrphium


2 Answers

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);
}
like image 151
Attila Avatar answered Aug 01 '26 08:08

Attila


A possibility would be to use std::vector with istream_iterator:

#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::istringstream in(std::string("a line from file"));

    std::vector<std::string> words;
    std::copy(std::istream_iterator<std::string>(in),
              std::istream_iterator<std::string>(),
              std::back_inserter(words));

    return 0;
}

The vector will grow as required to store whatever number of words is provided by the user.

like image 38
hmjd Avatar answered Aug 01 '26 08:08

hmjd