2011-09-29 73 views
1

为什么当输入数字时该循环执行3次?我只想''或'米'被接受..我怎么能解决这个问题?输入数字时出现循环错误

cout << "Are you married or single (m/s): "; 
    cin >> status; 
    status = tolower(status); //converting to lower case 

    //validating imput for marital status 
    while((status != 'm') && (status != 's')) 
    { 
     cout << "Sorry, you must enter \"m\" or \"s\" \n" 
       << "Are you married or single (m/s): "; 
     cin >> status; 
     status = tolower(status); 
    } 

回答

6

你的变量status可能是声明为:

char status; 

所以,cin >> status从输入读取一个字符。但是,您可能输入了多个输入,因为输入被缓冲,您需要按Enter键。

相反,使用此声明:

string status; 

这将让输入的整条生产线,然后你可以检查行内的字符。

+0

你应该说明的是3,可能是因为 “一\ r \ n” 个 –

+0

'\ r \ n'应该被流自动转换为'\ n'(我想'cin'自动处于文本模式)... –

+0

只有当它没有任何空格时才会得到整行输入。 .. – sth

0

您可以使用getchar()保存到状态, 它读取缓冲区只有一个字符..

cout << "Are you married or single (m/s): "; 
    getchar(status); 

    //validating imput for marital status 
    while((status != 'm') || (status != 's')) //status can be a male OR a female 
    { 
     cout << "Sorry, you must enter \"m\" or \"s\" \n" 
       << "Are you married or single (m/s): "; 
    getchar(status); 
    }