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!
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With