2016-07-21 5 views
1

프로그램에서 x를 정수로 허용하고 다른 정수 y를 요구하는 중입니다. 그러나 내가 x에 부동 소수점을 입력하면 입력의 소수 부분을 가져 와서 y 값이됩니다. 나는 나의 실수를 확신 할 수 없다. C++의 모든 콘솔 입력이 다음의 getInt() 다음 작업을 수행 할 것입니다 방법에 따라 문자열로 취급되기 때문에C++ 사용자가 정수 대신 부동 소수점을 입력합니다.

#include <iostream> 
#include <string> 
#include <limits> 
using namespace std; 

int getInt() 
{ 
    int x = 0; 
    while (!(cin >> x)) 
    { 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
     cout << "Please input a proper 'whole' number: " << endl; 
    } 
    return (x); 
} 

int toobig() 
{ 
    cout << "Your number is too large, please enter something smaller: " << endl; 
    int x = getInt(); 
    return (x); 
} 

int toosmall() 
{ 
    cout << "your number is negative, please enter a positive number: " << endl; 
    int x = getInt(); 
    return (x); 
} 


int main() 
{ 

    cout << "your number please:-" << endl; 
    int x = getInt(); 

    if (x>100000) 
    { 
     toobig(); 
    } 
    else if (x<0) 
    { 
     toosmall(); 
    } 

    int y = 0; 

    cout << "enter y " << endl; 
    cin >> y; 

    cout << "x = " << x << endl; 
    cout << "y = " << y << endl; 
    system("PAUSE"); 

    return 0; 
} 
+0

"Y"값은 무엇을 의미합니까? "123.456"을 입력하고이를 정수로 읽으면 123은 정수로 읽혀질 것입니다. – user3344003

+0

사용자가 첫 번째 정수 뒤에'. '을 입력했는지 확인할 수 있고 그 경우 오류를 반환 할 수 있습니까? – KABoissonneault

+0

예 x는 123입니다. 그러나이 값을 입력하면 프로그램은 즉시 X = 123 Y = 0을 인쇄합니다. –

답변

0

: 경우,

 int GetInt(istream &stream) 
     { 
     char obtainChar; //read a character from input 
     int x;  

     stream >> x; 

     while(stream.fail() || (stream.peek() != '\r' && stream.peek() != '\n')) 
     { 
      stream.clear(); //clear the fail state of stream 
      obtainChar = stream.get(); //read a character from input 

      while(obtainChar != '\n' && obtainChar != EOF) //while gotten char is not a return key or EOF 
       obtainChar = stream.get(); //read a character from input iterate up to '\n' or EOF 
      //displays an error message if there was a bad input (e.g. decimal value) 
      cerr << endl << "Please input a proper 'whole' number: " << endl; 
      cout << endl << "Please re-enter x: "; //re-prompt to re-enter a value 

      x = GetInt(stream); //Try again by calling the function again (recursion) 
     } 
      return x; //will return after the user enters ONLY if an integer was inputted 
    } 

처음 동안 기본적으로 말하고를 스트림 (콘솔 입력)이 실패하거나 다음 스트림 char (.peek())가 \ r 또는 \ n이 아닌 경우 스트림을 지우고 첫 번째 문자를 가져옵니다.

char은 \ n이 아니고 EOF (End Of File)가 아니고 다음 문자를 얻는 식으로 계속 진행됩니다.

문제가 발생하면 사용자에게 오류 메시지를 표시하고 사용자에게 x 값을 다시 묻습니다.

그런 다음 모두가 정상이면 x의 값을 반환하고 동일한 함수를 호출하여 재귀 적으로 입력을 테스트합니다 (재귀 적으로). istream로는 iostream 라이브러리의 일부가

참고 CIN 기본적으로 다음과 같습니다 :과 같이 함수를 호출 :

int x; 
cout << "your number please:-" << endl; 
x = GetInt(cin); 

당신은 지금

가 참고 Y의 가치를 평가하기 위해이 함수를 호출 할 수 있습니다

1

int으로의 변환은 int의 일부가 될 수없는 것을 발견하자마자 중단되며 전체 문자열을 구문 분석하기 전에 중지하는지 알려주는 변환 함수는 적습니다.

one of those few을 사용해 보겠습니다.

int getInt() 
{ 
    for (; ;) // loop until user provides something we can use. 
       // This is dangerous. You probably want to give up after a while. 
    { 
     std::string input; // read in as string 
     if (std::cin >> input) 
     { 
      char * endp; // will be updated with pointer to where conversion stopped 
      errno = 0; 

      // convert string to int 
      long rval = std::strtol (input.c_str(), &endp, 10); 
      if (*endp == '\0') // check whole string was read 
      { 
       if (errno != ERANGE) // check converted number did not overflow long 
       { 
        if (rval >= std::numeric_limits<int>::min() && 
         rval <= std::numeric_limits<int>::max()) 
         // check converted number did not overflow int 
         // you could replace this min and max with your own passed-in 
         // min and max values if you want 
        { 
         return rval; // return the known-to-be-good int 
        } 
       } 
      } 
     } 
     else 
     { // note: usually when cin fails to read a string, it's over. 
      // This is actually a good time to throw an exception because this 
      // just shouldn't happen. 
      std::cin.clear(); // but for now we'll just clear the error and 
           // probably enter an infinite loop of failure 
     } 
     // failed for any reason. Blow off all user input and re-prompt 
     std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
     std::cout << "Please input a proper 'whole' number: " << std::endl; 
    } 
    return 0; // to satisfy compiler because a non-void function must always return. 
       // Never reached because of infinite for loop. 
} 
관련 문제