前言
保存文件后查看发现显示乱码 · Issue #I7AOI7 · 天津中德应用技术大学开放原子开源社团/开放原子开源社团 - Gitee.com
社区出现以上问题 本文将围绕此问题解答
示例回顾
示例代码如下
#include <iostream>
#include<stdlib.h>
#include <fstream>
using namespace std;
struct Student//定义一个结构体 在此用于存储多种类型数据
{
int number;
string name;
double score;
};
void Write(Student &student)//将键盘输入写入txt文件
{
std::cin>>student.number>>student.name>>student.score;
ofstream outfile("test.txt",ios::out|ios::binary);
if(!outfile)
{
cerr<<"open test.txt error!"<<endl;
exit(1);
}
outfile.write((char*)&student,sizeof(student));
outfile.close();
}
void Find()//将txt文件中的数据读取出来
{
Student student;
ifstream infile("test.txt",ios::in|ios::binary);
if(!infile)
{
cerr<<"open test.txt error!"<<endl;
exit(1);
}
infile.read((char*)&student,sizeof(student));
cout<<"num:"<<student.number<<endl;
cout<<"name:"<<student.name<<endl;
cout<<"score:"<<student.score<<endl;
}
int main()
{
Student student;
Write(student);
Find();
return 0;
}
分析
输入结果后 读取会有一些问题 因为在C/C++中 有一个输入缓冲区的存在 在计算机看来 输入如下
1\nJack\n99.9 即每个回车(\n)都会被添加到缓冲区 计算机并不知道该如何将1\nJack\n99.9如何正确赋值到number name score
解决方案
也就是说 问题出在回车影响了计算机的判断 因此 我们需要使用一个getchar()吸收回车
代码如下
void Write(Student &student)//将键盘输入写入txt文件
{
cin>>student.number;
getchar();
cin>>student.name;
getchar();
cin>>student.score;
getchar();
ofstream outfile("test.txt",ios::out|ios::binary);
if(!outfile)
{
cerr<<"open test.txt error!"<<endl;
exit(1);
}
outfile.write((char*)&student,sizeof(student));
outfile.close();
}
也可以参照开放原子开源社团: 学习交流开源开发知识 - Gitee.com
链接里有笔者写的账户管理系统
总结
因为笔者编译器有优化 很难呈现出问题所在 getchar()并不一定要用这么多 建议读者自己尝试一下