c++文件操作乱码问题

c++中使用ifstream,ofstream,fstream实现对文件的读写操作,总是遇到乱码问题,

下面两个实例,解决乱码问题。


实例一:


//我们可以使所有的数组初始化为0,文件读取时,当读取到0时,就会停止读取!


#include <iostream>
#include <string>
#include <fstream>


using namespace std;


int main()
{




char name1[100]={0};
char name2[100]={0};

ofstream w;
w.open("text.txt");
if(!w.is_open())
{
 cerr<<"write file open error"<<endl;
}
cin>>name1;
w.write(name1,sizeof(name1));
w.close();


ifstream r;
r.open("text.txt");
if(!r.is_open())
{
cerr<<"read file open error"<<endl;
}
r.read(name2,sizeof(name2));
cout<<name2<<endl;
r.close();
}

实例二:


// \0作为字符串的结尾,我们可以使写入的内容,最后一个赋值为\0.


#include <iostream>
#include <string>
#include <fstream>


using namespace std;


int main()
{



    const int num=100;
char name1[num];
string str;
cin>>str;
int length=str.size();
length=length<num?length:num-1;
    str.copy(name1,length);
name1[length]='\0';

ofstream w;
w.open("text.txt");
if(!w.is_open())
{
 cerr<<"write file open error"<<endl;
}


w.write(name1,sizeof(name1));
w.close();


ifstream r;
r.open("text.txt");
if(!r.is_open())
{
cerr<<"read file open error"<<endl;
}

char name2[num];
r.read(name2,sizeof(name2));
cout<<name2<<endl;

r.close();
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值