如何从文件内容添加到二维数组?

时间:2018-12-09 21:19:05

标签: c++ file multidimensional-array

我在一个文件中有几行,每行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

如果有人可以在我的代码中找到错误进行修复,那将非常有帮助

1 个答案:

答案 0 :(得分:1)

使用编写循环的方式,将从文件中读取的每个数字分配给数组的所有元素。但是,当您退出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);
   }
}