By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,972 Members | 1,092 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,972 IT Pros & Developers. It's quick & easy.

istream and string

P: n/a
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

Apr 20 '06 #1
Share this Question
Share on Google+
4 Replies


P: n/a

<nn*******@gmail.com> wrote in message
news:11**********************@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
Apr 20 '06 #2

P: n/a
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

nn*******@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


Apr 20 '06 #3

P: n/a
ss*******@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
Apr 21 '06 #4

P: n/a
ss*******@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
Apr 22 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.