reading a word into a vector

how do i read 1 word from line of text and put it in a vector?
There are multiple lines in this file. Then I need to read the second word from each line... and so on and so forth. I know this is a noobie question but I am really stuck here
Use an std::string and std::getline()

To get each word, you can use std::string's .find() and .substr() to get the parts of the string you want. Look in the reference section on the site for info on these.
Here is an example of reading a file into a vector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int main()
{
  vector<string> file;
  vector<string> secondWord;

  ifstream in("file.txt", ios::in);

  string line = "";

  while(!in.eof())
  {
    getline(in, line);
    file.push_back(line);
  }

  // print out the file.. or do whatever
  for(int i = 0; i < file.size(); ++i)
  {
    cout << file[i] << endl;
  }

  // get second word from each line
  string temp;

  for(int i = 0; i < file.size(); ++i)
  {
    size_t first;
    size_t second;
    file[i].find(" ", first);
    file[i].find(" ", first, second);

    temp = file[i].substring(first+1, second);
    secondWord.push_back(temp);
  }

  return 0;
}


I did not compile this or test it but I think it should work.
It doesn't work because you aren't using string::find() correctly.
Topic archived. No new replies allowed.