将值复制到多维数组时出现问题

Problem Copying Values to Multidimensional Array

本文关键字:问题 数组 复制      更新时间:2023-10-16

我正在尝试编写一个可以从文本文件中获取 81 个整数并将它们添加到多维数组中的程序。

我正在从包含这些整数的文本文件中读取:

1  2  3  4  5  6  7  8  9 
10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27 
28 29 30 31 32 33 34 35 36 
37 38 39 40 41 42 43 44 45 
46 47 48 49 50 51 52 53 54 
55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72
73 74 75 76 77 78 79 80 81

这是我用来执行此操作的代码

int main() 
{
    ifstream myFile; //ifstream object
    int num[8][8]; //multidimensional array
    int TempStorage[80]; //temporary storage for reading numbers off of text file
    int maybe; //no clue what this one does
    int i=0; //used for temp storage input
    int x=0; //used to copy values to multidimensional array
    myFile.open("numbers.txt"); //open document
    if(myFile.is_open()) //check if document is open
    {
        while(myFile >> maybe) //while numbers are still on document
        {
            TempStorage[i] = maybe; //input numbers into temporary array
            i++; //index 
        }
        myFile.close(); //close document
        for(int n=0;n<9;n++) //first loop to control first index n
        {
            for(int q=0;q<9;q++) //second loop to control second index q        
            {
                num[n][q] = TempStorage[x];//read numbers into multidimensional array
                x++;    
            }
        }
    }
    return 0;
}

但是,当我输出存储在多维数组中的所有值时,我得到以下输出。出于某种原因,似乎前一个索引的值和第一个新索引的值相等。

1  2  3  4  5  6  7  8  10
10 11 12 13 14 15 16 17 19
19 20 21 22 23 24 25 26 28
28 29 30 31 32 33 34 35 37
37 38 39 40 41 42 43 44 46
46 47 48 49 50 51 52 53 55
55 56 57 58 59 60 61 62 64
64 65 66 67 68 69 70 71 73
73 74 75 76 77 78 79 80 1

我已经将 for 循环的条件更改为我能想到的几乎所有条件。这只是我忽略的一些非常简单的问题还是别的什么?

for(int n=0;n<9;n++) 

您的多维数组的大小为 [8],这意味着它可以从 0 到 7。