66

在以下代码中:

#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

由于 >> 运算符读取到第一个空格,所以我得到了这个输出。如何将行提取回字符串?

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

4

1 回答 1

104

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

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

因此,对于您的情况,它将是:

std::getline(read,x);
于 2011-07-12T11:01:40.447 回答