3

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.

semore_1267
  • 1,327
  • 2
  • 14
  • 29
NateEkat
  • 33
  • 3
  • Have you tried a space in double quotes instead of single? (as in a string instead of a char) ? – John3136 Apr 06 '17 at 22:32
  • @John3136 Yes, I have replaced ' ' with " ". I get the same results. – NateEkat Apr 06 '17 at 22:34
  • What do you mean by gibberish, exactly? – rici Apr 06 '17 at 22:38
  • @rici The following text is produced when the code is executed. '‷′″‰‰‰‱‵‹‶‰‰″‰′‰‰‸‸‰‰‰‱‰‰‰′‰‷‰‶‵‴‰′‰‰‰‴′‰‷″‰‰‰‵‰‹″‱‰‴‰‵‰‰‰‷‰‰‰″‴‰‰‱‰″‰‰‶‹″′‰‰‰‷‱‹' – NateEkat Apr 06 '17 at 22:40

1 Answers1

1

Depending on the IDE you're using, ending a file without an endl can cause problems. Solution:

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

Or if you want it to print out like a grid instead of a single line of text:

 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();
       }
    }
Jish
  • 92
  • 5