繁体   English   中英

C ++中的文件读取错误

[英]file reading error in C++

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

--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文件相同的内容。

你能帮我找出错误吗?

谢谢,Milind。

如果您的文件确实名为datalog.txt ,则应确保尝试打开该文件:

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

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

您指定的打开文件错误; 采用:

infile.open("datalog.txt");

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

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

可能只是您拼写错误的文件名吗? 您说该文件名为“ datalog.txt”,但是在代码中打开“ datalog”。

使用正确的文件名:-)然后,它对我有用。 “ 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循环而不是for循环来检查EOF:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM