如何将二维字符类型数组逐行保存到 c 中的.txt文件中

How to save a two dimensional char type array row-wise to a .txt file in c?

本文关键字:保存 逐行 中的 文件 txt 数组 类型 字符 二维      更新时间:2023-10-16

>我有一个二维字符数组[100][100],我想将其逐行保存到.txt文件中。我的意思是首先打印第一行中的所有字符,然后打印第二行,依此类推......

我可以编写控制台输出的代码,但不知道如何将其保存到.txt文件中:

for (int x=0;x<100;x++)
{
    for(int y=0;y<100;y++)
    {
        cout<<array[x][y];
    }
}

请在这方面帮助我。谢谢。

#include<iostream>
#include<fstream>
using std::cout;
int main(){
ofstream out("file_name.txt");
for(int x=0;x<100;x++){
        for(int y=0;y<100;y++){
              out << array[x][y];
        }
        out << "n";

}
file.close();
return 0;

}

使用 "n"; 而不是 endl; 会使您的代码更快,因为endl会刷新您的文件流缓冲区并将其写入您的文件每行 100 次。 因此,最好不要刷新文件流缓冲区,直到最后。 在这种情况下,关闭函数将刷新缓冲区并自动关闭它。

试试这个:

#include <fstream>
int main()
{
    std::ofstream out("file_to_store_the_array.txt");
    for(int x = 0; x < 100; x++) {
        for(int y = 0; y < 100; y++) {
            out << array[x][y];
        }
    }
    out.close();
    return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  for (int x=0;x<100;x++)
  {
    for(int y=0;y<100;y++)
    {
      myfile<<array[x][y]; 
    }
    myfile<<endl;
  }
  myfile.close();
  return 0;
}

不知道它是否编译,但粗略地应该向您展示如何完成。(<<ENDL;用于在行之间发出CR(或CR/LF,取决于系统)