2016-10-10 59 views
-2

如果我有一个文件,有一个64 * 64整数的表。 (第一个64将是第0行;第64个将是第1行,依此类推)。如何将该表格存储到二维数组中。 这里是我的代码从一个文件存储64 * 64整数到一个2D数组

#include <iostream> 
    #include <fstream> 
    using namespace std; 
    int main() 
    { 
     ifstream infile; 
     infile.open("table.txt"); 
     if (infile.fail()) 
     { 
      cout << "could not open file" << endl; 
      exit(6); 
     } 
     int array[63][63];  
     while (!infile.eof()) 
     { 
      infile >> array[63][63]; 
     } 
     cout << array[63][63] << endl; 
     return 0; 
    } 

时就执行我只得到“1”

+0

每次while循环迭代,要指定infile中导致成数组[63] [63],而不是改变X,Y(或任何索引)并填充整个数组。 –

+1

对此,[这是错误的:'while(!infile.eof())'](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-错误)。而且,你总是读取* same *元素,每次迭代覆盖。你的输出是一个单一的值,因为这是你的代码所做的;一个输出值:'cout << array [63] [63] << endl;'。我认为你需要重新审视你正在学习的语言的部分内容,因为这里有很多缺失。 – WhozCraig

+0

'infile >> array [63] [63];'这超出了界限并且是未定义的行为。 –

回答

0

而不是从文件分配值到数组[63] [63]您应该将其分配给一个元素,增加索引以填充整个阵列:

int x = 0; int y = 0; 
while (!infile.eof()) 
{ 
    infile >> array[x++][y]; 
    if (x > 63) 
    { 
     x = 0; 
     y++; 
    } 
} 

沿着这些方向的东西应该很好。

此外,如上所述,数组需要初始化为int数组[64] [64]。

1

我有一个表格为64 * 64整数(...)的文件如何将 表格存储到二维数组中?

首先,你必须声明合适大小的数组(当然,您应该考虑使用std::vectorstd::array代替,但你问一个二维数组):

const size_t size = 64; 
int array[size][size]; 

然后你必须在循环中分配它的每个元素。在您的代码中,由于您将数组声明为int array[63][63],所以您重复地写了元素array[63][63],该元素也在您分配的范围之外。请记住,数组从0开始,所以如果您为63 int s分配了足够的内存,则只有从0到62的数是有效的。

一种可能的方法来完成这项任务是:

for (size_t i = 0; i < size; ++i) 
{ 
    for (size_t j = 0; j < size; ++j) 
    { 
     if (!(infile >> array[i][j])) 
     { 
      std::cerr << "Too few elements were read from file\n"; 
      exit(7); 
     } 
    } 
} 
相关问题