How to Read a text file into a vector

...
Last edited on
closed account (48T7M4Gy)
This is a common problem. Best idea is to read up these two tutorials. Then have a go and show us any of your code you need a help on.

http://www.cplusplus.com/doc/tutorial/files/
http://www.cplusplus.com/reference/vector/vector/push_back/
This is what I had so far but I know the file isn't stored in a vector.

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()

{

ifstream (textfile);
textfile.open("lab2.txt");


if(textfile.fail()){
cerr << "Error Opening file" << endl;
exit(1);
}


return 0;
}
closed account (48T7M4Gy)
Use the 'Text file' section of the tutorial and practice with the sample program there to read the data from your text file. Something like this. Once you get the program to display the data you then add the values to a vector etc etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  int score = 0;
  string line;

  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile >> score)
    {
      cout << score << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}
Topic archived. No new replies allowed.