gpt4 book ai didi

c++ - C++文件读取错误

转载 作者:行者123 更新时间:2023-11-30 01:21:02 26 4
gpt4 key购买 nike

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

--数据日志.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 文件相同的地方。

你能帮我找出错误吗?

谢谢,温和。

最佳答案

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

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

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

关于c++ - C++文件读取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18658624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com