gpt4 book ai didi

c++ - 读取数据文件并将每一列分配给单独的数组

转载 作者:太空宇宙 更新时间:2023-11-04 11:40:05 24 4
gpt4 key购买 nike

我是 C++ 的初学者,我在将列从数据文件导入到单个数组时遇到问题。我的数据文件看起来像这样:

1 81 0 79 89 
2 81 0 79 89
3 81 0 79 89
4 81 0 79 89
5 81 0 79 89
6 81 0 79 89
7 81 0 79 89
8 81 0 79 89
9 81 0 79 89
10 81 0 79 89

现在我要做的是将前三列导入到单独的数组中。例如,数组“happinessseries1”(与第 2 列关联)的值应为 {81,81,81,81,81,81,81,81,81,81}。

我的代码是这样的:

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{

ifstream inFile;

int neglible[100]; //size of arrays bigger than number of entries in data file
int happinessseries1[100];
int happinessseries2[100];

int i=0;
inFile.open("happiness.dat");
if (inFile.fail())
{
cout << "Error" << endl;
return 1;
}
while (!inFile.eof())
{
inFile >> neglible[i];
inFile >> happinessseries1[i];
inFile >> happinessseries2[i];
i++;

cout << happinessseries1[i] << endl; // display values in the array to check that the correct values have been imported
}
inFile.close();

return 0;

}

为 happinessseries1 显示的值与原始列值不同。任何人都可以看到我的代码中有什么问题以及如何更正它。这也是我第一次发布问题,所以如果我需要澄清任何问题,请告诉我。提前致谢!

最佳答案

你需要交换这两行:

i++;
cout << happinessseries1[i] << endl; // display values in the array to check that the correct values have been imported

您正在递增 i,然后打印出第 i 个元素的值——尚未设置!你应该打印,然后递增。

关于c++ - 读取数据文件并将每一列分配给单独的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21708078/

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