如何将二维字符类型数组逐行保存到 c 中的.txt文件中
How to save a two dimensional char type array row-wise to a .txt file in c?
>我有一个二维字符数组[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,取决于系统)
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- 打印逐行存储的文本文件
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- C++如何将字符串逐行转换为双精度
- 在 c++ 中逐行阅读字符串,不要以空格停止
- 使用 QT 逐行读取 JSON
- 逐行读取文件,并将数据插入变量和数组中
- 逐行从文本文件中读取 |C++
- 我遇到使用 c++ 逐行读取输入文件的问题
- 无法逐行读取.csv文件
- 在 c++ 中逐行读取文件(将代码从 Python 转换为 C++)
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- C ++ txt 文件成数组逐行字符串和 int 用于纸牌游戏
- 如何将文件逐行读取到矢量中,然后打印矢量
- C++逐行读取文件
- 如何逐行读取文件并分隔行组件?
- C++ 逐行从文件(包含空格)读取数据
- 对包含整数的文本文件进行排序时,必须逐行进行排序
- C++ 循环逐行写入文件还是添加到数组并在循环后写入文件?
- 如何将二维字符类型数组逐行保存到 c 中的.txt文件中