istream and string

N

nnandini8

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
 
M

Mike Wahler

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
 
S

sshakir56

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
 
B

benben

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?=

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,
 

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
473,755
Messages
2,569,536
Members
45,019
Latest member
RoxannaSta

Latest Threads

Top