2011-09-29 4 views
1

숫자 입력시이 루프가 3 번 실행되는 이유는 무엇입니까? 나는 단지 's'또는 'm'이 받아 들여지기를 원한다. 어떻게 해결할 수 있을까?숫자 입력시 루프 오류

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 입력에서 단일 문자를 읽습니다. 그러나 입력이 v 퍼링되고 Enter를 눌러야하기 때.에 둘 이상을 입력했을 것입니다.

대신,이 선언 사용

string status; 

입력의 전체 라인을 얻을 것이다, 그리고 당신은 라인 내에서 문자를 검사 할 수 있습니다.

+0

당신은 3 아마 때문에 "는 \ r에 \ n" –

+0

'의 것을 설명해야한다 \ 연구 \ 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); 
    }