Reading a string from ifstream to 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 the operator reads to the first space, I get this output. How can I extract a string back to a string?

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

+47
c ++ string getline ifstream
Jul 12 '11 at 10:59
source share
1 answer

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

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

So, for your case it will be:

 std::getline(read,x); 
+83
Jul 12 '11 at 11:01
source share



All Articles