C++中的文件读取错误
file reading error in C++
我有一个非常简单的代码,但我无法找出错误。任务:我想读取包含浮点/双精度值的文本文件。文本文件如下所示:
--数据日志.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() 函数会更好
相关文章:
- C++-从文本文件读取矢量错误
- 增加 gil 读取图像错误
- C++访问冲突读取位置错误
- 使用DPI从C 函数中从SV中的读取值错误
- 使用 valgrind 时获得 int 变量指针的无效读取大小错误
- 使用 valgrind 的地图中的读取大小错误无效
- 瓦尔格林德无效读取大小 4 错误
- 无法修复访问冲突读取位置错误
- 为什么开始读取返回错误ENOMEM(_B)
- 如何修复访问冲突读取位置错误
- 从Android Java读取二进制错误UE4-C++
- VS 2012 调试 处理<文件时出现意外的符号读取器错误.exe>
- 处理 POSIX 套接字读取() 错误
- C、Linux 中的串行端口读取/打开错误
- C++:std::复制失败,出现访问冲突读取位置错误
- 从文本文件/文本流中读取Q字符串错误
- C++“访问冲突读取位置”错误
- (Qt)在尝试使用MainWindow上另一个小部件类的任何函数时出现读取访问错误
- read()返回在某些系统上读取的错误字节数
- 在c++中读取文件错误