@关于 C++ 中fprintf()函数处理string数据引发中断的问题解决方法
void Student::SaveInfo(void)
{
FILE * p;
p = fopen(“d:\wenjian.txt”, “w”);//建立一个文件的txt文件
fprintf(p, “%s\t%s\t%s\t%s\t%s\n”, “学号”, “姓名”, “性别”, “年龄”, “平均分”);
for (int i = 0; i < Num; i++)//向文件中输入数据
{
fprintf(p, “%d\t%s\t%s\t%d\t%d\n”, St[i].id, St[i].name, St[i].gender, St[i].age, St[i].ave);
};
fclose ( p );
}
原始代码如上,想要实现将学生信息保存为txt文件的功能,梦想中的效果图如下
其中学号、年龄、平均分为int类型数据
姓名,性别为string类型数据
这段代码编译时没有任何问题,但是运行到该行代码是会引发中断。
将代码中涉嫌string类型的数据删除,没有任何问题,确定为fprintf()函数不能完美地处理string数据。
最终解决方法如下
void Student::SaveInfo(void)
{
FILE * p;
p = fopen(“d:\wenjian.txt”, “w”);//建立一个文件的txt文件
fprintf(p, “%s\t%s\t%s\t%s\t%s\n”, “学号”, “姓名”, “性别”, “年龄”, “平均分”);
for (int i = 0; i < Num; i++)//向文件中输入数据
{
fprintf(p, “%d\t%s\t%s\t%d\t%d\n”, St[i].id, St[i].name.c_str(), St[i].gender.c_str(), St[i].age, St[i].ave);//fprintf()函数没办法对string数据进行操作,需要在string数据后面加上.c_str()
};
fclose ( p );
}
在string类型数据后面加上 .c_str();
完美解决。