1

I have a space delimited text file, from which I need to extract individual words to populate a vector<string>.

I've tried playing around with strtok, but I understand this is not working because strtok returns a char pointer. Any way to extract the words from the file, and fill the string vector with them? Thanks!

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
AlmostSurely
  • 552
  • 9
  • 22
  • 1
    `ifstream fin(filename); string word; fin >> word;` – Beta Jun 23 '12 at 01:48
  • 1
    [This answer](http://stackoverflow.com/a/237280/1336150) might help you too... – Eitan T Jun 23 '12 at 01:57
  • 1
    possible duplicate of [How to read in space-delimited information from a file in c++](http://stackoverflow.com/questions/2530738/how-to-read-in-space-delimited-information-from-a-file-in-c) – Bo Persson Jun 23 '12 at 02:09

2 Answers2

5

There are "fancier" ways, but in my opinion the following's most understandable (and useful as a basis for variations) for beginners:

if (std::ifstream input(filename))
{
    std::vector<std::string> words;
    std::string word;
    while (input >> word)
        words.push_back(word);
}
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • 1
    Just in case you're curious what's meant by fancier, `std::vector vec ((std::istream_iterator(in)), std::istream_iterator());`, where `in` is the `ifstream` object. – chris Jun 23 '12 at 02:01
2

Consider using an ifstream to read the file.

Then you can use the >> operator to move the next word into the string.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
EvilTeach
  • 28,120
  • 21
  • 85
  • 141