std::getline

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*型への変換演算子を用いて状態を判断している。
匿名さん、ありがとう。

以上

コスミー について

昔(?)はゲーム作ってました。 今もなんか作ろうとしています。
カテゴリー: C++ パーマリンク

std::getline への6件のフィードバック

  1. 匿名 のコメント:

    getlineはifsの参照を返すので、

    std::ifstream ifs(“hoge.txt”);
    std::string line;
    while ( ! std::getline(ifs, line)) {
    std::cout << line << std::endl;
    }

  2. コスミー のコメント:

    本文を修正しました。
    あと、!いらないですよね。

  3. 匿名 のコメント:

    > あと、!いらないですよね。

    そうですね…orz
    コピペして消し忘れました。すみません。

  4. may chay bo ho chi minh のコメント:

    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!

  5. Diane のコメント:

    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.

  6. Enid のコメント:

    I am truly happy to glance att this weblog posts
    which includes tons of valuable information, thanks for providing such statistics.

コメントを残す

メールアドレスが公開されることはありません。