Read contents of text file.

J

Jason Heyes

How do you read the contents of a text file into a std::string? Does this
code use the right classes and functions for the job?

std::string s;
char c;
while (is.get(c))
s += c;

Thanks.
 
J

James Daughtry

Well, if you need the entire contents of the file in a single string,
your loop will work, though there are other ways of doing it. You could
use getline for example:

std::string file;
std::string line;

while (std::getline(is, line))
file += line;

Or you could use a stringstream and rdbuf:

std::eek:stringstream oss;
oss << in.rdbuf();
std::string file = oss.str();

There's no 'right' way to do it, just try whatever comes to mind and
see if it does what you want and has acceptable performance.
 
J

Jason Heyes

James Daughtry said:
Well, if you need the entire contents of the file in a single string,
your loop will work, though there are other ways of doing it. You could
use getline for example:

std::string file;
std::string line;

while (std::getline(is, line))
file += line;

Or you could use a stringstream and rdbuf:

std::eek:stringstream oss;
oss << in.rdbuf();
std::string file = oss.str();

There's no 'right' way to do it, just try whatever comes to mind and
see if it does what you want and has acceptable performance.

Ok. I'll use my loop for the time being.
 
M

Marcelo Pinto

while (std::getline(is, line))
file += line;

I believe you should add the newline caracter at the end of each line:

while (std::getline(is, line))
file += line + "\n";

Good luck,

Marcelo Pinto
 
J

James Daughtry

It depends on how you plan to use it. For situations where the newline
would be needed, it's usually better to place each line in a container
of strings rather than one big string. I left the decision open since
the OP didn't specify how the string was going to be used.
 

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

Forum statistics

Threads
474,204
Messages
2,571,066
Members
47,672
Latest member
svaraho

Latest Threads

Top