how can i read file and store data into string?

as title, i wanna know how to read file and store it into string

1
2
3
4
5
6
7
8
9
10
11
string file = "test.txt";
string str;//where data should be store in
ifstream fin;
fin.open(file.c_str());
if (!fin){
   cout << "ERROR - Unable to access " << file << endl;
   exit(0);}
while(!fin.eof()){
   /*insert all the data into str;
}
fin.close(); */


the test.txt include a long article in it with alpha, digit, space and punct.
1
2
3
4
5
6
7
8
9
...
while( !fin.eof() ) {
  //insert all the data into str
  string line;
  getline( fin, line ); //read a line of data
  str.append(line); //store that line
  str.append("\n"); //or whatever delimeter you want in between the lines
}
fin.close();


string: http://cplusplus.com/reference/string/string
Also see, stringstream: http://cplusplus.com/reference/iostream/stringstream
Topic archived. No new replies allowed.