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

被折叠的 条评论
为什么被折叠?



