0

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

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 的类型错误,我就无法识别错误消息。

4

1 回答 1

2

我觉得:

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;
    }
}

会做你想做的。

于 2013-04-02T05:38:46.393 回答