이 질문에 약간 stackoverflow std::cin.clear() fails to restore input stream in a good state에 비슷한 질문이 있지만 거기에 제공된 대답은 나를 위해 작동하지 않습니다.스트림의 상태를 리셋
질문 : 어떻게 스트림의 상태를 '양호'로 다시 재설정 할 수 있습니까?
여기 내 코드는 어떻게 사용합니까?하지만 상태는 다시 좋게 설정되지 않습니다. 두 줄을 따로 따로 사용했습니다.
는int _tmain(int argc, _TCHAR* argv[])
{
int result;
while (std::cin.good())
{
std::cout << "Choose a number: ";
std::cin >> result;
// Check if input is valid
if (std::cin.bad())
{
throw std::runtime_error("IO stream corrupted");
}
else if (std::cin.fail())
{
std::cerr << "Invalid input: input must be a number." << std::endl;
std::cin.clear(std::istream::failbit);
std::cin.ignore();
std::cin.ignore(INT_MAX,'\n');
continue;
}
else
{
std::cout << "You input the number: " << result << std::endl;
}
}
return 0;
}
내 책에는 다음과 같이 말합니다 : clear (flag)는 지정된 조건 상태를 유효하게 설정합니다. 나는 이것을 다음과 같이 해석했다. 지정된 오류 비트를 지운다. 이것은 틀린가? – physicalattraction
* all * 플래그를 지우는 것은 단지'clear()'입니다. 단일 플래그를 지우려면 좀 더 복잡합니다 (너무 유용하지는 않습니다). 내 대답에 새로운 부분을 추가했습니다. –