std::getlineってよく使い方分からないんだけど、どうなんだ。fstreamのgetlineも同じ話だと思うけど、いつeofになるのか。たぶん最後まで読み込んだ時点ではeofにならない。その次にgetlineしたときに何も読み込めなくて、eofになるんじゃないかなあ。
なので、
std::ifstream ifs("hoge.txt");
std::string line;
while (!ifs.eof()) {
std::getline(ifs, line);
std::cout << line << std::endl;
}
こんな感じにすると最後空文字列が出力される気がする。というわけで下のようにしてる。
std::ifstream ifs("hoge.txt");
std::string line;
while (true) {
std::getline(ifs, line);
if (ifs.eof()) break;
std::cout << line << std::endl;
}
追記(2009/04/13):
ってやってたんだけども上記はバグ。最後の行に改行がない場合、lineに読み込めていてもifs.eof()がtrueを返すので最後の行を出力する前にbreakしてしまう。
正しくは下記。(匿名さんの投稿より)
std::ifstream ifs("hoge.txt");
std::string line;
while ( std::getline(ifs, line)) {
std::cout << line << std::endl;
}
getlineはifsの参照を返すのでその状態を調べるという。入出力ストリーム(basic_ios)は!演算子をオーバーロードしていて、「!ifs」などでfail()とかそういうのを呼び出してくれるので
if(!ifs) {
}
って感じで状態を調べられる。上記では!演算子ではなくvoid*型への変換演算子を用いて状態を判断している。
匿名さん、ありがとう。
以上
getlineはifsの参照を返すので、
std::ifstream ifs(“hoge.txt”);
std::string line;
while ( ! std::getline(ifs, line)) {
std::cout << line << std::endl;
}
本文を修正しました。
あと、!いらないですよね。
> あと、!いらないですよね。
そうですね…orz
コピペして消し忘れました。すみません。
Wow, wonderful weblog layout! How lengthy have you been running a blog for?
you make running a blog look easy. The full look of your web site is excellent, as smartly as the content
material!
Great goods from you, man. I have understand your stuf previous to and you’re just extremely fantastic.
I actually like what you’ve acquired here, certainly like what you are
stating and the way in which you say it.
Youu maoe it entertaining and you still care
for to keep it smart. I cant wait to read much more from you.
This is actually a great website.
I am truly happy to glance att this weblog posts
which includes tons of valuable information, thanks for providing such statistics.