2017-12-30 6 views
2

これはC++入門第5版の17章(17.5.3)のサンプルコードです。C++入門第5版第17.5.3項fstreamは改行しない

int main(void) { 

    fstream inOut("test.txt", fstream::ate | fstream::in | fstream::out); 
    if (!inOut) 
    { 
     cerr << "Unable to open file!" << endl; 
     return EXIT_FAILURE; 
    } 

    auto end_mark = inOut.tellg(); 
    inOut.seekg(0, fstream::beg); 
    size_t cnt = 0; 
    string line; 

    while (inOut && inOut.tellg() != end_mark && getline(inOut, line)) 
    { 
     cnt += line.size() + 1; 
     auto mark = inOut.tellg(); 
     inOut.seekg(0, fstream::end); 
     inOut << cnt; 

     if (mark != end_mark) 
     { 
      inOut << " "; 
     } 

     inOut.seekg(mark); 
    } 

    inOut.seekg(0, fstream::end); 
    inOut << "\n"; 
    return 0; 
} 

ファイルtest.txtの内容は次のとおりです。このファイルには、空白行で終わる場合

abcd 
efg 
hi 
j 
<This is a blank new line> 

ポイントは、ある、それは予想だとして、このコードは動作します。

abcd 
efg 
hi 
j 
5 9 12 14 
<This is a blank new line> 

をしかし、ファイルが空白改行で終わっていない場合、それはこのような出力は以下となります:他の言葉では、それがこのにファイルを変更します

abcd 
efg 
hi 
j5 9 12 

(注)このことファイルは新しい行で終わらない。 私の質問は、空白の改行はどこですか?その後、コードがあります

inOut << "\n"; 

いずれの場合も新しい空白行を挿入する必要があります。どこが間違っていますか?

答えて

2

ファイルの最後に到達すると、ストリームの不良ビットが設定されるという問題があります。あなたが最終的INOUT < <「\ n」は改行の前に

inOut.clear(); 

を追加する場合、期待どおり改行なしのラインの長さが追加されないように続けていますが、書かれています。

+0

テスト済みです。魅力のように働きます。 :)私は第8章(8.1.2)をレビューしますが、これについて言及しています。 – callofdutyops

関連する問題