c++ - 无法使用 ofstream 写入空格,但 endl 工作正常

标签 c++ ofstream 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.close();
   }
}

这会产生一个充满乱码的文件:

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

但是如果我用 endl 替换空格字符,它的输出就很好。

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

所以我的问题变成了,如何将我的数组输出到文件,并用空格而不是 endl 分隔整数。

此外,如果有更详细解释这一点的位置,请随时链接。感谢所有帮助。

最佳答案

根据您使用的 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();
       }
    }

关于c++ - 无法使用 ofstream 写入空格,但 endl 工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43266754/

相关文章:

c++ - C++ 中的复活节星期天

C++/Tk : can we create an executable that would run with out requiering end user to have any special TcL interpriter installed?

c++11 - 流的初始值设定项列表 (C++11)

c++ - 如果我想从输入文件(例如1、2、3)中读取逗号分隔的数据,包括逗号?

c++ - 使用 '\n' 而不是 endl 会影响输出,为什么?

c++ CDialog ID 更改

c++ - 使用 fstream 向所有用户发送消息

c++ - 逐列写入文件 C++

c++ - 流缓冲区实现的 std::endl 和 '\n' 之间的差异

c++ - 发送 std::endl 到流给出内存地址