Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   istream and string (http://www.velocityreviews.com/forums/t453487-istream-and-string.html)

nnandini8@gmail.com 04-20-2006 07:49 PM

istream and string
 
Hello guys,
I have a small doubt in istream.
I have a file calles infile.txt
infile.txt contains Hello World
now I wanted to add these contents to a string.
ie i need to have hello world in a string
Note there is a space between Hello and WOrld

Any help will be greatly appreciated
Thank You
Nandini


Mike Wahler 04-20-2006 08:00 PM

Re: istream and string
 

<nnandini8@gmail.com> wrote in message
news:1145562553.080352.110940@i39g2000cwa.googlegr oups.com...
> Hello guys,
> I have a small doubt in istream.
> I have a file calles infile.txt
> infile.txt contains Hello World
> now I wanted to add these contents to a string.
> ie i need to have hello world in a string
> Note there is a space between Hello and WOrld
>
> Any help will be greatly appreciated


// (error checking omitted)
#include <fstream>
#include <iostream>
#include <string>

int main()
{
std::ifstream ifs("infile.txt");
std::getline(ifs, line);
std::cout << "string contains: " << line << '\n';
return 0;
}

-Mike



sshakir56@gmail.com 04-20-2006 09:36 PM

Re: istream and string
 
Thanks for the reply Mike.
It worked but what do I need to do if I have like
hello
world
in 2 seperate lines
Thanks in advance

Nandini

nnandini8@gmail.com wrote:
> Hello guys,
> I have a small doubt in istream.
> I have a file calles infile.txt
> infile.txt contains Hello World
> now I wanted to add these contents to a string.
> ie i need to have hello world in a string
> Note there is a space between Hello and WOrld
>
> Any help will be greatly appreciated
> Thank You
> Nandini



benben 04-21-2006 01:38 AM

Re: istream and string
 
sshakir56@gmail.com wrote:
> Thanks for the reply Mike.
> It worked but what do I need to do if I have like
> hello
> world
> in 2 seperate lines
> Thanks in advance


Use another getline to get the next line.

Regards,
Ben

=?ISO-8859-1?Q?Ney_Andr=E9_de_Mello_Zunino?= 04-22-2006 02:24 AM

Re: istream and string
 
sshakir56@gmail.com wrote:

> Thanks for the reply Mike.
> It worked but what do I need to do if I have like
> hello
> world
> in 2 seperate lines


Here's an alternative solution:

#include <fstream>
#include <sstream>
#include <string>
#include <iostream>

int main()
{
using std::ifstream;
using std::stringstream;
using std::string;
using std::cout;

ifstream file("Test.txt");
stringstream buffer;
buffer << file.rdbuf();
string contents = buffer.str();

cout << "Contents: " << contents << '\n';
}

Regards,

--
Ney André de Mello Zunino


All times are GMT. The time now is 02:35 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.