2014-01-28 35 views
-1

我有包含带随机数的20x20矩阵的文件。我读过文件中的数字,然后存储在数组中。看来我实际上并没有将数字赋给数组,因为当我打印其中一个数字时,它显示了类似“||”而不是数字,请参阅行cout <<array[0][1]。我的完整代码如下:存储阵列后无法处理文件中的数据

#include<iostream> 
#include<fstream> 
#include<iomanip> 
using namespace std; 
#define length 20 

int main(){ 

    char array[length][length]; 

    char chs; 


    ifstream grid; 
    grid.open("D:\\Example\\digit.txt", ios::in); 
    while (!grid.eof()){ 
     for (int i = 0; i < 19; i++){ 
      for (int j = 0; j < 19; j++){ 
        grid.get(chs); 
        if (!grid.eof()){ 
         array[i][j] = chs; 
         cout << setw(1) << array[i][j];///It display the numbers on file, there is no problem here.*/ 
        } 
      } 
     } 
    } 

cout <<array[0][2];//There is problem it can not display the number it display something different than numbers. 
grid.close(); 
while (1); 
} 

CONSOL的输出,文件上的数字看起来像这样。 cout <<array[0][3]不打印

Output of the consol, the numbers on the file exactly look like this 我已经改变了最后一部分

cout << endl; 
    for (int i = 0; i < 19; i++){ 
     for (int j = 0; j < 19; j++){ 

       cout << array[i][j]; 
      } 
     } 
    cout << endl; 
    grid.close(); 

输出比对文件编号不同的最后一部分的唯一

enter image description here

+0

您声明20的长度变量,然后不使用它们,并使用19的魔术数字为您的读取过程..这不是问题,但这是非常糟糕的。 – UpAndAdam

回答

2

你内环运行的当前值为i,这意味着您在第一行读取任何值,在第二行读取第一个值。

for (int i = 0; i < 19; i++){ 
    for (int j = 0; j < i; j++){ 
//     ^wrong 

如果要读取20x20的矩阵,则内部和外部循环都应运行20次迭代。

for (int i = 0; i < 19; i++){ 
    for (int j = 0; j < 19; j++){ 
//      ^^ 

还要注意,您可能需要添加一些代码来处理输入文件中的任何换行符。每组20位数字后,您将有一个(\n)或两个(\r\n)字符表示换行符。这些是文本文件的有效部分,但可能不需要存储在您的阵列中。

+0

我已经改变了这一点,在这个时候cout << array [0] [1]什么也没有显示 – user2970691

+0

它适用于我(忽略我添加到我的答案中的换行符问题)。你可以向你的问题添加一个示例输入文件并更新代码片段作为一个完整的程序吗? – simonc

+0

我已经编辑了我的问题simonc – user2970691