-
File I/O and Strings
Hello,
I usually don't like to post on this forum because I would rather read a book or try and work it out myself, but for some reason I am just completely stuck on this.
What I am trying to do, is load a text file from start to finish loading each line into a vector of strings.
For example, if the file contained:
hello
this
is
a
forum
Then a vector of strings
vector <string>
0 would be hello
1 would be this
2 would be is
3 would be a
4 would be forum
I have been trying to do this with the fstream.h header file, but I am just continually getting errors, or compile problems.
I would post code, but I have attempted it so many times I wouldn't know which one to paste. I am looking for an example now.
Thanks for any help, and please keep the flames to a minimum.
- Chris
-
Something like -
Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
//Assumes text file is in program dir
ifstream i("t.txt");
vector<string> s;
copy(istream_iterator<string>(i),istream_iterator<string>(),back_inserter(s));
copy(s.begin(),s.end(),ostream_iterator<string>(cout,"\n"));
return 0;
}
-
Code:
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> TheLines;
string currentLine;
fstream input ("input.txt");
while( ! input.eof() )
{
getline(input,currentLine);
TheLines.push_back(currentLine); //add the current line to the end of the vector
}
input.close();
return(0);
}
That is another way of doing it with out using the algorithim header file, which is sometimes easier to under stand for beginners