reading a line from ifstream into a string variable

C++StringIfstreamGetline

C++ Problem Overview


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 ?

C++ Solutions


Solution 1 - C++

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

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

So, for your case it would be:

std::getline(read,x);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuhail GuptaView Question on Stackoverflow
Solution 1 - C++jonscaView Answer on Stackoverflow