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 ?

jww
  • 97,681
  • 90
  • 411
  • 885
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • 1
    See also the suggestions here: http://stackoverflow.com/questions/116951/using-fstream-to-read-every-character-including-spaces-and-newline – Itamar Katz Jul 12 '11 at 11:15

1 Answers1

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);
thiagowfx
  • 4,832
  • 6
  • 37
  • 51
jonsca
  • 10,218
  • 26
  • 54
  • 62
  • 16
    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: http://gehrcke.de/2011/06/reading-files-in-c-using-ifstream-dealing-correctly-with-badbit-failbit-eofbit-and-perror – Dr. Jan-Philip Gehrcke Jan 18 '15 at 14:50