首页 文章

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

提问于
浏览
0

我在文件中有几行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 回答

  • 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);
       }
    }
    

相关问题