2

Okay, this may seem a simple question; but I can't seem to find an answer to it. My code is as follows:

void writeFile(int grid[9][9]) {
   ofstream fout ("myGame2.txt");
   if (fout.is_open()) {
      for (int i = 0; i < 9; i++) {
         for (int j = 0; j < 9; j++) {
            fout << grid[i][j] << ' ';
         }
      }
      fout.close();
   }
}

This produces a file full of gibberish:

‷′″‰‰‰‱‵‹‶‰‰″‰′‰‰‸‸‰‰‰‱‰‰‰′‰‷‰‶‵‴‰′‰‰‰‴′‰‷″‰‰‰‵‰‹″‱‰‴‰‵‰‰‰‷‌​‰‰‰″‴‰‰‱‰″‰‰‶‹″′‰‰‰‷‌​‱‹'

But if I replace the space character with an endl, it outputs just fine.

fout << grid[i][j] << endl;

So my question becomes, how do I output my array to the file, and separate the integers with a space instead of an endl.

Also, if there is a location that explains this in greater detail, please feel free to link it. All help is appreciated.

4

1 回答 1

0

根据您使用的 IDE,结束没有 endl 的文件可能会导致问题。解决方案:

void writeFile(int grid[9][9]) {
   ofstream fout ("myGame2.txt");
   if (fout.is_open()) {
      for (int i = 0; i < 9; i++) {
         for (int j = 0; j < 9; j++) {
            fout << grid[i][j] << ' ';
         }
      }
      fout << endl;
      fout.close();
   }
}

或者,如果您希望它像网格一样打印而不是单行文本:

 void writeFile(int grid[9][9]) {
       ofstream fout ("myGame2.txt");
       if (fout.is_open()) {
          for (int i = 0; i < 9; i++) {
             for (int j = 0; j < 9; j++) {
                fout << grid[i][j] << ' ';
             }
             fout << endl;
          }
          fout.close();
       }
    }
于 2017-04-06T22:46:28.123 回答