How to Read a text file into a vector
Jan 19, 2017 at 11:18pm UTC
...
Last edited on Jan 20, 2017 at 3:40am UTC
Jan 19, 2017 at 11:45pm UTC
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/
Jan 20, 2017 at 12:00am UTC
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;
}
Jan 20, 2017 at 12:48am UTC
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.