how to let a string value be the entire contents of .txt

how to let a string value be the entire contents of .txt

string g = all the contents of happy.txt

how to do it?

do others file's ending (e.g. .exe) also work?
Last edited on
I think you can read file line by line and insert readed string to stringstream
1
2
3
4
5
6
7
8
9
10
11
12
13
14
stringstream ss;
string str,tmp;

fstream fs;
fs.open("happy.txt");
while(!fs.eof())
{
getline(fs,tmp);
ss <<tmp;

}

str=ss.str();
cout <<str;
hi, NULL
how do i know when i should stop to getline?
while(!fs.eof())
will stop getline.
btw, the tutorial below just show feof, and why do u use fs.eof? --> faster running speed??
http://www.cplusplus.com/reference/clibrary/cstdio/feof/

and what is ths " stringstream ss" ?

i can't search " fs.eof " at the top of this forum~ ~

http://www.cplusplus.com/forum/beginner/3952
above post also haven't mention what is the advantage of using #include <sstream>
rather than #include <string>
Last edited on
Please don't suggest people stop on ifstream::eof(). Any input error at all will cause you an infinite loop. Test against istream::good().
1
2
3
4
5
while (fs)
  {
  getline(fs,...
  ...
  }


Alternative methods:
1
2
3
4
5
6
#include <fstream>
#include <string>
ifstream f( ... );
string s, ln;
while (getline( f, ln )) s += ln + "\n";
f.close();
1
2
3
4
5
6
#include <fstream>
#include <string>
ifstream f( ... );
string s;
getline( f, s, '\0' );  // this presumes that there are no null characters in the file
f.close();
1
2
3
4
5
6
7
8
9
10
11
12
#include <algorithm>
#include <fstream>
#include <iterator>
ifstream f( ... );
string s;
f >> noskipws;
copy(
  istream_iterator <char> ( f ),
  istream_iterator <char> (),
  back_inserter( s )
  );
f.close();
1
2
3
4
5
6
7
8
9
10
11
#include <fstream>
#include <string>
ifstream f( ... );
string s;
streamsize n;
f.seekg( 0, ios::end );
s.resize( n = f.tellg() );
f.seekg( 0, ios::beg );
f.read( const_cast <char*> (s.c_str()), n );
s.resize( f.gcount() );
f.close();

These last two are interesting... The istream_iterator works using >>, alas, so it is rather slow... The final one has the multiple resizing to account for newline conversions...

Hope this helps.
Thanks veey much, Duoas, you show 4 alternative methods..

my .txt is big, i use the first 2 method~ ~

and why the 4th method need to resize , don't get the size of .txt and use fread then already finished?


besides, my program have some convert << Number; //number to string

as you say << is slow, another simpler, quicker method of doing integer to string?

thanks
Last edited on
Topic archived. No new replies allowed.