AlmostSurely
AlmostSurely

Reputation: 562

C++ Populate a vector of strings from a space-delimited text file

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!

Upvotes: 1

Views: 3366

Answers (2)

EvilTeach
EvilTeach

Reputation: 28837

Consider using an ifstream to read the file.

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

Upvotes: 2

Tony Delroy
Tony Delroy

Reputation: 106086

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

Upvotes: 5

Related Questions