reading a line from ifstream into a string variable

烂漫一生 提交于 2019-11-26 07:38:39

问题


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 ?


回答1:


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

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

So, for your case it would be:

std::getline(read,x);


来源:https://stackoverflow.com/questions/6663131/reading-a-line-from-ifstream-into-a-string-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!