![]() |
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 |
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 |
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 |
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 |
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 05:51 PM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.