tags:

views:

1502

answers:

2

I want to load separately the words on a text file like

text.txt

Hi this is a text file 
with many words
I don't know how many

into a vector<string> how do I go about it?

+3  A: 

I'll give you the general algorithm rather than the code.

  1. Open the text file in code. C++ has iostream and fstream headers to assist with this.
  2. Until you reach EOF, read one line at a time.
  3. For each line in step 2, split the line on a space (google string tokenizer)
  4. For each token from step 3, add to a vector
  5. Close the file
Alan
thanks but I'm pretty stuck when getting the tokens. I've tried using an interator and gotten an empty vector. I'm time-pressed ,so a clear piece of c++ code will be greatly appreciated.
omgzor
Try this: http://codepad.org/xyUYo4yf I got from here http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
Alan
thanks, problem solved.
omgzor
A: 

What about this:

#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main(int argc, char* argv[]) {
    vector<string> strings;

    string word;
    ifstream input(argv[1]);
    while(!input.eof()) {
     input >> word;
     strings.push_back(word);
    }

    return 0;
}

It depends what kind of delimiter you'd be using really.

Ray Hidayat
That code contains a dangerous error leading to an endless loop in some cases. See my answer in the other thread for an explanation.
Konrad Rudolph