从txt文件到数组的输入数字(Input Numbers from txt file to array)

编程入门 行业动态 更新时间:2024-10-23 09:24:01
从txt文件到数组的输入数字(Input Numbers from txt file to array)

我很确定这是一个常见的问题,但我找不到类似于我的例子,所以..我有一个名为input.txt的文本文件,其中包含:0.0001234 1.0005434 0.0005678 1.0023423 0.00063452 1.0001546 0.00074321 1.00017654。 现在我想写一个程序将其读入一个数组,然后快速检查它是否有效。 到目前为止,我有:

#include <iostream> #include <fstream> #include <string> using namespace std; int main () { double PA[8]; int n; ifstream myfile ("input.txt"); if (myfile.is_open()) { while (! myfile.eof() ) { getline (myfile,line); cout << PA[line]<< endl; } myfile.close(); } else cout << "Unable to open file"; for (n=0; n<8; n++) // to print the array, to check my work { cout << " {" << PA[n] << "} "; } system("PAUSE"); return 0; }

到目前为止,我的问题是我不断收到错误:未声明行。 我想稍后使用浮点数来计算新数据。 我觉得我做错了..有什么帮助吗? 谢谢!

I'm pretty sure that this is a common question, but I can't find an example similar to mine, so.. I have a text file called input.txt that has: 0.0001234 1.0005434 0.0005678 1.0023423 0.00063452 1.0001546 0.00074321 1.00017654 in it. Now I want to write a program to read that into an array, and then quickly check that it worked. So far, I've got:

#include <iostream> #include <fstream> #include <string> using namespace std; int main () { double PA[8]; int n; ifstream myfile ("input.txt"); if (myfile.is_open()) { while (! myfile.eof() ) { getline (myfile,line); cout << PA[line]<< endl; } myfile.close(); } else cout << "Unable to open file"; for (n=0; n<8; n++) // to print the array, to check my work { cout << " {" << PA[n] << "} "; } system("PAUSE"); return 0; }

My problem so far is that I keep getting the error: line was not declared. And I want to use the array later with floats to calculate new data. I think I'm doing it wrong for that.. Any help? Thanks!

最满意答案

声明行变量

int n, line = 0; std::string value;

适当的加载数据:

getline (myfile,value); PA[line] = atof(value.c_str()); cout << PA[line]<< endl; line++;

declare line variable

int n, line = 0; std::string value;

proper load data:

getline (myfile,value); PA[line] = atof(value.c_str()); cout << PA[line]<< endl; line++;

更多推荐

本文发布于:2023-08-03 13:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391369.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   数字   文件   txt   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!