그래. try-catch 문은 루프 안에 있습니다. 그래서 무언가를 시도해보십시오. 실패하고 예외가 발생하면 예외를 잡아 내고 루프에서 빠져 나가거나 다시 돌아 오지 않으므로 같은 일을 반복해서 수행하게됩니다.
하지만 입력이 처음 처리되지 않았으므로 (대신) 예외가 처리되었으므로 두 번째 또는 세 번째 또는 임의의 시간에 처리되지 않습니다. 일반적으로, 그런데
int input;
while (1 == 1){
cout << "Enter a number: ";
try{
cin.exceptions(istream::failbit);
cin >> input;
}catch(ios::failure){
cout << "Not a number\n";
input = 0;
//the line below ignores all characters in cin until the space (' ')
//(up to 256 characters are ignored, make this number as large as necessary
cin.ignore(256, ' ');
}
}
: 발전하려면
, 다음 공간까지 입력을 무시하여 예외를 처리 예외가 오버 헤드가 특히 때문에, 진정으로 특별한 뭔가를해야한다 예외 처리 용. whether invalid user input is exceptional에 대한 논쟁이 있습니다.
는 다른 방법으로, 다음과 같은 예외없이 훨씬 더 작고, 똑같이 올바른 루프를 만들 수 있습니다
int input;
while (true){ //outer while loop that repeats forever. Same as "while(1 == 1)"
cout << "Enter a number: ";
//The following loop just keeps repeating until a valid value is entered.
//The condition (cin >> input) is false if e.g. the value is a character,
//or it is too long to fit inside an int.
while(!(cin >> input)) {
cout << "Not a number" << endl;
input = 0;
}
}
당신은 정말로 참고로 붙잡아 야합니다 –