getline 语句未获取输入

getline statement is not getting the input

本文关键字:输入 获取 语句 getline      更新时间:2023-10-16
//class
class student
{
    public:
    int rno;
    string name;
    int marks;
    int ran;
    void getinfo()
    {   a:
        cout<<"t tenter the roll number"<<endl;
        cin>>rno;
        cout<<"t tenter the name"<<endl;
        getline(cin,name);
        cout<<"t tenter the marks"<<endl;
        cin>>marks;
    }
    void showinfo()
    {
        cout<<"t"<<ran<<"t "<<rno<<"  tt"<<name<<" tt"<<marks<<endl<<endl;
    }
};

当我在为卷号输入后在控制台中获取对象的输入时,它正在打印"输入名称",然后没有任何机会给出输入,它正在显示下一个打印语句"输入标记"。 Getline 语句没有从控制台获取输入有什么原因吗?

cin将在缓冲区中保留新行。 因此,当您从cin获取rno时,cin缓冲区中实际上会剩下一个n。 当你去读名字时,它只是抓住n并立即返回。在第一个cin之后执行类似 cin.ignore(); 的操作应该会清除缓冲区并允许您正确读取用户输入。