저는 C++ 프로그래밍을 시작하고 많은 입력 검증을해야합니다. 나는이 기능이 보편적으로 적용되는 것처럼 보였지만, 한 가지면에서 문제가있다. -90을 입력하면 프로그램에서 오류가 발생하지 않습니다. 내 질문은 : 1. 입력이 < = 0이 될 수 없다는 상황을 어떻게 추가 할 수 있습니까? 2. 사용자 입력을 제한하는 더 좋은 방법이 있습니까? C++ 내 라이브러리일까요?C++ 입력 유효성 확인
도움이나 조언을 제공해 주셔서 감사합니다.
#include <ios> // Provides ios_base::failure
#include <iostream> // Provides cin
template <typename T>
T getValidatedInput()
{
// Get input of type T
T result;
cin >> result;
// Check if the failbit has been set, meaning the beginning of the input
// was not type T. Also make sure the result is the only thing in the input
// stream, otherwise things like 2b would be a valid int.
if (cin.fail() || cin.get() != '\n')
{
// Set the error state flag back to goodbit. If you need to get the input
// again (e.g. this is in a while loop), this is essential. Otherwise, the
// failbit will stay set.
cin.clear();
// Clear the input stream using and empty while loop.
while (cin.get() != '\n')
;
// Throw an exception. Allows the caller to handle it any way you see fit
// (exit, ask for input again, etc.)
throw ios_base::failure("Invalid input.");
}
return result;
}
사용
inputtest.cpp
#include <cstdlib> // Provides EXIT_SUCCESS
#include <iostream> // Provides cout, cerr, endl
#include "input.h" // Provides getValidatedInput<T>()
int main()
{
using namespace std;
int input;
while (true)
{
cout << "Enter an integer: ";
try
{
input = getValidatedInput<int>();
}
catch (exception e)
{
cerr << e.what() << endl;
continue;
}
break;
}
cout << "You entered: " << input << endl;
return EXIT_SUCCESS;
}
T의 유효한 범위를 지정하는 선택적 매개 변수는 무엇입니까? – crashmstr
'getValidatedInput'에서 오류 처리가 잘못되었습니다. 입력이 파일에서 왔고 (리디렉션으로 인해) 파일의 끝 부분에 있다면 어떻게 될까요? –
'-90'은 유효한 'int'이므로, 함수의 실패는 다소 놀랍습니다. 정확성을 위해 * 특정 입력을 구문 분석하는 방법은 다양합니다. "일반 유효성 검사"에 관해서도, 나는 왜 그런 기능이 필요한지 알지 못합니다. 입력을 읽고'cin'을 체크하면 거기에 유효성이 있습니다. – DevSolar