【问题标题】:How to ignore the empty line at the end of input如何忽略输入末尾的空行
【发布时间】:2013-04-02 05:31:41
【问题描述】:

以下代码工作正常,还检查用户是否输入了正确数量的项目,但当输入有一个尾随空行时它会失败。

string item1, item2, item3;
while(cin.good) {

    //this allows me to both check if user input enough items 
    //EDIT: and if items are of right type so I can cerr
    if (cin >> item1 && cin>> item2 && cin>> item3) {

        doStuff(item1,item2,item3);

    }else {

        cerr<<"bad input! Not enough input items or wrong type"<<endl;

    }

}

我可以将 cin.good 更改为其他内容以解决尾随空行的情况吗?我也会接受其他解决方案。

编辑: 我意识到我不能使用 while(cin >> item1),因为如果 item1 的类型错误,我就无法识别错误消息。

【问题讨论】:

    标签: c++ input newline cin


    【解决方案1】:

    我认为:

    while(cin >> item1) {
        //this allows me to check if user input enough items
        if (cin >> item2 && cin >> item3) {
            doStuff(item1,item2,item3);
        } else {
            cerr<<"bad input! Not enough input items"<<endl;
        }
    }
    

    会做你想做的。

    【讨论】:

    • 抱歉,我才意识到我需要原始的 if 语句,因为我还需要检查和确认项目类型的正确性。
    猜你喜欢
    • 2021-04-08
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多