Question

I have file that contains 20x20 matrix with random numbers. I've read the numbers on the file and then to store in the array. It seems I had not actually assign the numbers to array, because when I had print one of the number it displayed something like "||" instead of number, see the line cout <<array[0][1]. My complete code is below:

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

Output of the consol, the numbers on the file exactly look like this. cout <<array[0][3] does not print

Output of the consol, the numbers on the file exactly look like this I've changed the last part

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

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

Output of the last part that is different than numbers on the file

enter image description here

Was it helpful?

Solution

Your inner loop only runs for the current value of i, meaning that you read no values into the first row, 1 into the second row etc.

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

If you want to read a 20x20 matrix, both your inner and outer loop should run for 20 iterations.

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

Note also that you probably need to add some code to handle any newlines in your input file. After each set of 20 digits, you'll have one (\n) or two (\r\n) characters indicating a newline. These are a valid part of the text file but presumably aren't required to be stored in your array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top