[c++] reading a line from ifstream into a string variable

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 ?

This question is related to c++ string ifstream getline

The answer is


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

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

So, for your case it would be:

std::getline(read,x);

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to ifstream

Read text file into string. C++ ifstream reading a line from ifstream into a string variable How does ifstream's eof() work? Open file by its full path in C++

Examples related to getline

When and why do I need to use cin.ignore() in C++? Using getline() with file input in C++ Using getline() in C++ c++ Read from .csv file cin and getline skipping input Why is reading lines from stdin much slower in C++ than Python? Going through a text file line by line in C reading a line from ifstream into a string variable