关于C/C++键盘输入缓冲区的问题

文章讨论了在C++中进行文件读写时遇到的乱码问题,原因是输入缓冲区的回车字符影响了数据赋值。解决方案是使用getchar()函数吸收多余的回车。通过修改Write函数,为每个输入项后添加getchar(),可以避免这个问题。文章还提供了一个简单的账户管理系统的链接作为参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

 

保存文件后查看发现显示乱码 · 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()并不一定要用这么多 建议读者自己尝试一下

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值