1

私は非常に単純なコードを持っていますが、間違いを見つけることができません。タスク: float/double 値を含むテキスト ファイルを読みたいです。テキスト ファイルは次のようになります。

--datalog.txt--

3.000315
3.000944
3.001572
3.002199
3.002829
3.003457
3.004085
3.004714
3.005342
3.005970
3.006599
3.007227
3.007855
3.008483
3.009112
3.009740
3.010368
3.010997

コードは次のようになります

--dummy_c++.cpp--

#include <iostream>
#include <fstream>
#include <stdlib.h> //for exit()function
using namespace std;

int main()
{
  ifstream infile;
  double val;

  infile.open("datalog");

  for (int i=0; i<=20; i++)
    {
      if(infile >> val){
    cout << val << endl;
      } else {
    cout << "end of file" << endl;
      }
    }
  return 0;
}

出力は次のようになります。

end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file
end of file

期待どおり、datalog.txt ファイルと同じように出力されます。

間違いを見つけるのを手伝ってもらえますか?

ありがとう、ミリンド。

4

6 に答える 6

3

ファイルが実際に呼び出されdatalog.txtている場合は、それを開こうとすることを確認する必要があります。

infile.open("datalog.txt");
//                  ^^^^^^

完全なパスを指定しない場合、exe は現在のディレクトリでそれを探します。

于 2013-09-06T13:10:35.817 に答える
1

Could it be that you simply mispelled the file name? You say the file is called "datalog.txt" but in the code you open "datalog".

于 2013-09-06T13:11:25.293 に答える
0

おっしゃる通り、ファイル名は"datalog.txt". 使用しているコードで"datalog". また、ストリームを使用した後は必ずストリームをチェックして、ファイルが正しく開かれたことを確認してください。

int main()
{
    std::ifstream infile;
    double val;

    infile.open("dalatog.txt");

    if( infile )
    {
        for(unsigned int i = 0 ; i < 20 ; ++i)
        {
            if(infile >> val)
                std::cout << val << std::endl;
            else
                std::cout << "end of file" << std::endl;
        }
    }
    else
        std::cout << "The file was not correctly oppened" << std::endl;
}

さらに、EOF をチェックする for ループの代わりに while ループを使用することをお勧めします。

while( infile >> val )
{
    std::cout << val << std::endl;
}
于 2013-09-06T13:18:19.963 に答える
0

適切なファイル名を使用してください:-)それは私にとってはうまくいきます。「datalog」ファイルには、ところで、20 行ではなく、18 行しかありません。

于 2013-09-06T13:13:19.553 に答える
-1

おそらく std::getline() 関数を使用する方が良いでしょう

于 2013-09-06T13:23:25.020 に答える