6

次のコードを使用して、ファイルを1行ずつ文字列型変数に読み込もうとしています。

#include <iostream>
#include <fstream>


ifstream file(file_name);

if (!file) {
    cout << "unable to open file";
    exit(1);
}

string line;
while (!file.eof()) {
    file.getline(line,256);
    cout<<line;
}
file.close();

Stringクラスを使おうとするとコンパイルされず、char file[256]代わりに使用した場合にのみコンパイルされます。

どうすれば行ごとに文字列クラスに入れることができますか?

4

1 に答える 1

11

使用std::getline

std::string s;
while (std::getline(file, s))
{
    // ...
}
于 2010-04-05T23:28:56.377 に答える