Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 349
Suhail Gupta Avatar asked Jul 12 '11 10:07

Suhail Gupta


People also ask

Is ifstream a variable?

An ifstream variable has an open function which can be used to open a file. The name of the file is a parameter to the open function. Once this is done, you can read from the ifstream object in exactly the same way you would read from cin.


1 Answers

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

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

So, for your case it would be:

std::getline(read,x); 
like image 73
jonsca Avatar answered Oct 02 '22 17:10

jonsca