C++中的文件读取错误

file reading error in C++

本文关键字:读取 取错误 文件 C++      更新时间:2023-10-16

我有一个非常简单的代码,但我无法找出错误。任务:我想读取包含浮点/双精度值的文本文件。文本文件如下所示:

-

-数据日志.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

正如我所期望的那样,它将打印与数据记录.txt文件相同。

你能帮我找到错误吗?

谢谢米林德。

如果你的文件真的被调用datalog.txt你应该确保你尝试打开它:

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

如果您没有完全路径化,exe 将在当前目录中查找它。

您指定了要打开的错误文件;请使用:

infile.open("datalog.txt");

您可以通过简单的测试来防止尝试使用未打开的文件:

infile.open("datalog.txt");
if (infile) {
    // Use the file
}

难道你只是拼错了文件名?你说该文件被称为"datalog.txt",但在代码中你打开了"datalog"。

使用正确的文件名 :-)那么,它对我有用。顺便说一句,"数据日志"文件只有 18 行,而不是 20 行。

正如您所说,文件名为 "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;
}

此外,最好使用 while 循环而不是检查 EOF 的 for 循环:

while( infile >> val )
{
    std::cout << val << std::endl;
}

也许使用 std::getline() 函数会更好