Connecting Tech Pros Worldwide Forums | Help | Site Map

Read contents of text file.

Jason Heyes
Guest
 
Posts: n/a
#1: Jul 23 '05
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.



James Daughtry
Guest
 
Posts: n/a
#2: Jul 23 '05

re: Read contents of text file.


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::ostringstream 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.

Jason Heyes
Guest
 
Posts: n/a
#3: Jul 23 '05

re: Read contents of text file.


"James Daughtry" <mordock32@hotmail.com> wrote in message
news:1117628246.600747.224300@z14g2000cwz.googlegr oups.com...[color=blue]
> 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::ostringstream 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.
>[/color]

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


Marcelo Pinto
Guest
 
Posts: n/a
#4: Jul 23 '05

re: Read contents of text file.


>while (std::getline(is, line))[color=blue]
> file += line;[/color]

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

Alex Vinokur
Guest
 
Posts: n/a
#5: Jul 23 '05

re: Read contents of text file.



"Jason Heyes" <jasonheyes@optusnet.com.au> wrote in message news:429da3a2$0$5383$afc38c87@news.optusnet.com.au ...[color=blue]
> 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?[/color]
[snip]

Reading file to string (29 ways):
http://groups-beta.google.com/group/...5e065030?hl=en

--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn


James Daughtry
Guest
 
Posts: n/a
#6: Jul 23 '05

re: Read contents of text file.


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.

Closed Thread