reading a line from ifstream into a string variable
Asked Answered
C

1

68

In the following code :

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

using namespace std;

int main() {
    string x = "This is C++.";
    ofstream of("d:/tester.txt");
    of << x;
    of.close();


    ifstream read("d:/tester.txt");
    read >> x;
    cout << x << endl ;
}

Output :

This

Since >> operator reads upto the first whitespace i get this output. How can i extract the line back into the string ?

I know this form of istream& getline (char* s, streamsize n ); but i want to store it in a string variable. How can i do this ?

Circumstantial answered 12/7, 2011 at 10:59 Comment(1)
See also the suggestions here: #117451Coequal
I
107

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);
Ignitron answered 12/7, 2011 at 11:1 Comment(1)
The return value of getline() (a stream object) should be evaluated in a bool expression. Bool evaluation of the stream object does a very important trick here: it evaluates failbit and badbit of the underlying stream. One should make use of that. A more in-depth explanation can be found here: gehrcke.de/2011/06/…Combustion

© 2022 - 2024 — McMap. All rights reserved.