reading a line from ifstream into a string variable
174,704
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
Author by
Suhail Gupta
"There's nothing more permanent than a temporary hack." - Kyle Simpson "The strength of JavaScript is that you can do anything. The weakness is that you will." - Reg Braithwaite I am on internet Twitter @suhail3 E-mail [email protected]
Updated on July 05, 2022Comments
-
Suhail Gupta almost 2 years
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 ? -
Dr. Jan-Philip Gehrcke over 9 yearsThe 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 evaluatesfailbit
andbadbit
of the underlying stream. One should make use of that. A more in-depth explanation can be found here: gehrcke.de/2011/06/…