0

I am given a file with characters like this test case:

+++X..X---
++++XX----

When I try to read from the file into the 2d array like I do bellow, the result changes every time I run the code. Sometimes it reads/prints properly , and others it only prints some of the chars ,without throwing any errors. How could I fix this?

  int main() {
        ifstream myFile;
        myFile.open("map");
        int N = 1000; //max size
        int M = 1000;
        char map_universe[N][M];

        noskipws(myFile);
        char a;
        int i = 0;
        int j = 0;
        while (!myFile.eof()) {
            myFile >> a;
            if (a != '\r' && !myFile.eof()) {
                map_universe[i][j] = a;
                cout << map_universe[i][j];
                j++;   
             } else {
                i++;
                j = 0;
            }
        }
        myFile.close();
Celia
  • 41
  • 3
  • add `cout << endl;` after `j = 0;` line. – Sergey Kalinichenko Apr 01 '18 at 13:48
  • `int N = 1000; int M = 1000;char map_universe[N][M];` -- This is not valid C++. In C++, arrays must have their sizes denoted by compile-time constants not variables. You are using a non-standard, compiler extension called "Variable Length Arrays". It is not actually C++. Also, you are risking blowing out the stack if `N` or `M` are sufficiently large. If you want to use standard C++ and not risk stack issues, use `std::vector> map_universe(N, std::vector(M));`. – PaulMcKenzie Apr 01 '18 at 13:53

0 Answers0