读写文件的格式要一模一样

本文详细介绍了使用C++中的stringstream和sscanf_s进行文件读写时,确保读写格式完全一致的重要性。通过具体代码示例,阐述了如何避免因格式不匹配导致的数据读取错误,如乱码等问题,强调了在处理中文字符和特殊符号时的注意事项。

使用 sstream 类的 stringstream 和 sscanf_s 写读文件的时候
两边的格式要一模一样

s << "姓名:" << name  << "\t\t年龄:" << age << endl;
"姓名:%s 年龄:%d"

中的中文要一样 冒号要一样 不能是读文件全角 写文件半角 不能写文件中文 读文件英文
否则 读出来的就是乱码
写文件

int main(void){
	string name;
	int age;
	ofstream outfile;



	outfile.open("use.txt",ios::out|ios::trunc);
	if (outfile.fail()) {
		cerr << "文件打开失败" << endl;
	}
	while (1) {
		cout << "输入姓名(Ctrl+z退出):";
		cin >> name;
		if (cin.eof()) {
			break;
		}
		cout << "输入年龄:";
		cin >> age;
		/*string a = "\t\t";
		string b = "\t";*/
		stringstream s;
		
		s << "姓名:" << name  << "\t\t年龄:" << age << endl;//读和写的格式要一模一样
		
		
		

		outfile << s.str(); //转为 string
	
	}
	outfile.close();

	system("pause");
	return 0;
}

读文件

int main(void)
{
	char name[32];
	int age;
	string line;
	ifstream infile;
	infile.open("use.txt");

	while (1) {
		getline(infile, line);
		if (infile.eof()) { //判断文件是否结束
			break;
		}

		sscanf_s(line.c_str(),"姓名:%s 年龄:%d", name, sizeof(name), &age); //读和写的格式要一模一样
		cout << "姓名:" << name << "\t\t年龄:" << age << endl;
	}

	infile.close();

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值