2013-04-02 31 views
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是错误的类型,我不能使用错误消息。

回答

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

会做你想要什么。

+0

对不起,但我只是意识到我需要原始的if语句,因为我还需要检查和cerr项目类型的正确性。 – Arch1tect