나중에 파일에서 유효성을 검사하는 사용자로부터 정수 ID를 가져 오는 코드를 작성 중입니다. 이제 cin에 유효한 입력을 입력하지 않으면 (분명히) 작동하지 않습니다. 다음과 같은 샘플 코드를 첨부했습니다.
std::cout << "Enter ID : " << std::endl;
std::cin >> id;
그렇게 간단합니다. 이제 입력과 같은 a
또는 다른 문자를 입력 하면 cin.fail ()을 사용하여 오류를 확인할 수 있지만 입력을 입력 11a
하면 작동하지 않는 것 같습니다. 인터넷에서 많이 검색했지만 적절한 해결책을 찾지 못했습니다.
먼저 Stack에 오신 것을 환영합니다. 이 시도
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin, theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
나는 그것을 시각화하기 위해 출력을 만들었다. "inputAsInt"변수는 추가 작업이 필요한 변수입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다