cin for c ++中int的字符串输入问题

时间:2014-11-08 14:53:23

标签: c++ string error-handling

所以在我的代码中:

#include <iostream>    
using namespace std;

int main ()
{    
    int choice;    
    cout<<"Make a choice\n";    
    cin>>choice;    
    cin.ignore();    
    while ( choice != 5 ) {    
        cout<<"Make a different choice!\n";    
        cin>>choice;    
        cin.ignore();    
    }
    cout<<"You weren't supposed to enter 5!";        
}

这适用于输入数字,但是当我输入一个字符串(即a)时,程序只需写入

"Make a different choice!\n"

无限次!如何处理可能的字符串输入?

0 个答案:

没有答案