【问题标题】:getline statement is not getting the input [duplicate]getline 语句没有得到输入[重复]
【发布时间】:2018-03-17 09:38:17
【问题描述】:
//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<<"  \t\t"<<name<<" \t\t"<<marks<<endl<<endl;
    }

};

当我在为 roll no 提供输入后在控制台中获取对象的输入时,它正在打印“输入名称”,然后没有任何机会提供输入,它正在显示下一个打印语句,即“输入分数”。 getline 语句没有从控制台获取输入有什么原因吗??

【问题讨论】:

  • 使用cin.ignore()

标签: c++ string class io getline


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-06
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2012-11-12
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多