2014-09-04 2 views
4

저는 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; 
} 
+1

T의 유효한 범위를 지정하는 선택적 매개 변수는 무엇입니까? – crashmstr

+0

'getValidatedInput'에서 오류 처리가 잘못되었습니다. 입력이 파일에서 왔고 (리디렉션으로 인해) 파일의 끝 부분에 있다면 어떻게 될까요? –

+0

'-90'은 유효한 'int'이므로, 함수의 실패는 다소 놀랍습니다. 정확성을 위해 * 특정 입력을 구문 분석하는 방법은 다양합니다. "일반 유효성 검사"에 관해서도, 나는 왜 그런 기능이 필요한지 알지 못합니다. 입력을 읽고'cin'을 체크하면 거기에 유효성이 있습니다. – DevSolar

답변

1

std::istream::operator >>strtol, strtoul으로 정의하고, 사촌 * 불행하게도 모두가 변함에도 서명되지 않은 유형의 마이너스 기호를 허용하는됩니다.

기본적으로 서명 된 int 입력을 수락하고 결과를 0과 비교하면됩니다. std::cin.setf(std::ios::failbit)은 인위적으로 변환 예외를 발생 시키므로 변환 함수가 오류시 작동하는 방식을 정렬 할 수 있지만 실제로 도움이되지는 않을 수 있습니다.

* operator >>strto*의 관점에서 정의된다 scanf의 관점에서 정의된다 std::num_get의 관점에서 정의된다. 모두가 막 돈을 넘겼지만, strtoul은 확실히 결함이 있습니다.

0
  1. 템플릿 매개 변수로 unsigned int를 사용하십시오.
  2. 입력 만 유효하고 허용되지 않는 입력에 대한 규칙을 설정할 수 있습니다.
1

당신은 사용을

template <typename T> 
T getValidatedInput(function <bool(T)> validator) { 
    T tmp; 
    cin >> tmp; 
    if (!validator(tmp)) { 
     throw ios_base::failure("Invalid input."); 
    } 
    return tmp; 
} 

나는이 필요하시면 희망

int input = getValidatedInput<int>([] (int arg) -> bool { 
    return arg >= 0; 
}); 
0

의 유효성을 검사하는 기능을 사용할 수 있습니다, 그것은 제로 입력시의를 종료하지만, 음수를 표시합니다. 입력 catch 메소드로 인해 예외 오류가 발생합니다.

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

void inputcatch() 
{ 
    cin.clear(); 
    cin.ignore(cin.rdbuf()->in_avail()); 
} 

int main() 
{ 
    int input; 
    bool quit = false; 
    while (!quit) 
    { 
     cout << "Enter number" << endl; 
     cin >> input; 
     if (cin.fail()) 
     { 
      inputcatch(); 
      cout << "incorrect input" << endl; 
     } 
     else if (input == 0) 
     { 
      quit = true; 

     } 
     else 
     { 
      cout << "your number: " << input << endl; 
     } 
    } 
    return 0; 
}