从ifstream读取一行到字符串变量

Suh*_*pta 59 c++ string getline ifstream

在以下代码中:

#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 ;
}
Run Code Online (Sandbox Code Playgroud)

Output :

This

由于>> operator读取到第一个空格,我得到了这个输出.如何将线提​​取回字符串?

我知道这种形式,istream& getline (char* s, streamsize n ); 但我想将它存储在一个字符串变量中. 我怎样才能做到这一点 ?

jon*_*sca 99

使用std::getline()from <string>.

 istream & getline(istream & is,std::string& str)
Run Code Online (Sandbox Code Playgroud)

所以,对于你的情况,它将是:

std::getline(read,x);
Run Code Online (Sandbox Code Playgroud)

  • 应该在bool表达式中评估`getline()`(流对象)的返回值.Bool对流对象的评估在这里做了一个非常重要的技巧:它评估底层流的`failbit`和`badbit`.人们应该利用它.可以在此处找到更深入的解释:http://gehrcke.de/2011/06/reading-files-in-c-using-ifstream-dealing-correctly-with-badbit-failbit-eofbit-and-perror (13认同)