Read text file into std::string.

J

Jason Heyes

Shezan Baig said:
Sorry, wasn't thinking. It should be:

std::stringstream ss;

ss << is.rdbuf();

now you can do whatever you want with 'ss.str()'.

Hey it works! Thanks for the neat trick.
 
J

Jason Heyes

Shezan Baig said:
Sorry, wasn't thinking. It should be:

std::stringstream ss;

ss << is.rdbuf();

now you can do whatever you want with 'ss.str()'.

Here in.eof() equals false:

bool read_file(std::string name, std::string &s)
{
std::ifstream in(name.c_str());
if (!in.is_open())
return false;

std::stringstream ss;
ss << in.rdbuf();

if (!in.eof())
return false;

s = ss.str();
return true;
}

When a loop is used, in.eof() equals true. Why the difference?
 
S

Shezan Baig

Jason said:
Here in.eof() equals false:

bool read_file(std::string name, std::string &s)
{
std::ifstream in(name.c_str());
if (!in.is_open())
return false;

std::stringstream ss;
ss << in.rdbuf();

if (!in.eof())
return false;

s = ss.str();
return true;
}

When a loop is used, in.eof() equals true. Why the difference?


Because this code reads from the filebuf, which has no notion of eof,
badbit etc. If you need to check eof or other failures, you can do it
the other way round:

is >> ss.rdbuf();

hth,
-shez-
 
J

Jason Heyes

Shezan Baig said:
Because this code reads from the filebuf, which has no notion of eof,
badbit etc. If you need to check eof or other failures, you can do it
the other way round:

is >> ss.rdbuf();

I tried this with the eof checking enabled. I lost all "\n\t" sequences.
Very peculiar.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top