我在一个文件中有几行 5 个不同的值,我想使用该文件创建一个二维数组,其中主数组中的每个数组都有 5 个值,我想将这些值添加到数组中直到主数组中存在20个子数组或到达文件末尾
然而,对于我的代码,根本没有现有的输出,我不知道发生了什么
#include <iostream>
#include <fstream>
const int row = 20;
const int column = 5;
using namespace std;
int main()
{
double temperature[row][column];
double temp;
ifstream inFile;
inFile.open("grades1.txt");
if (inFile) //if the input file to be read open successfully then goes on
{
while (inFile >> temp) //reads through file
{ //adds answers to the array
// Inserting the values into the temperature array
for (int i = 0; i < row; i++)
{
for(int j = 0; j < column; j)
{
temperature[i][j] = temp;
}
}
}
for(int i=0; i<row; i++) //This loops on the rows.
{
for(int j=0; j<column; j++) //This loops on the columns
{
cout << temperature[i][j] << " ";
}
cout << endl;
}
}
}
这是我用的温度文件
61.4 89.5 62.6 89.0 100.0
99.5 82.0 79.0 91.0 72.5
如果有人能在我的代码中找到错误并修复它,那将非常有帮助
最佳答案
按照您编写循环的方式,将从文件中读取的每个数字都分配给数组的所有元素。但是,当您退出 while
循环时,只会保留最后读取的数字。
读取数字的代码需要在最内层循环。
for (int i = 0; i < row; ++i)
{
for(int j = 0; j < column; ++j)
{
if ( inFile >> temp )
{
temperature[i][j] = temp;
}
}
}
当到达文件末尾时,您希望能够停止进一步的读取尝试。最好使用一个函数来读取数据,并在到达 EOF 或读取数据时出现任何其他类型的错误时从函数返回。
在此期间,您不妨使用函数来打印数据。
#include <iostream>
#include <fstream>
const int row = 20;
const int column = 5;
using namespace std;
int readData(ifstream& inFile, double temperature[row][column])
{
for (int i = 0; i < row; ++i)
{
for(int j = 0; j < column; ++j)
{
double temp;
if ( inFile >> temp )
{
temperature[i][j] = temp;
}
else
{
return i;
}
}
}
return row;
}
void printData(double temperature[][column], int numRows)
{
for(int i=0; i<numRows; i++)
{
for(int j=0; j<column; j++)
{
cout << temperature[i][j] << " ";
}
cout << endl;
}
}
int main()
{
ifstream inFile;
inFile.open("grades1.txt");
if (inFile)
{
double temperature[row][column] = {};
int numRows = readData(inFile, temperature);
printData(temperature, numRows);
}
}
关于c++ - 如何从文件内容添加到二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696768/