input - C++ user enters floating point instead of integer -


im trying program accept x integer ask integer, y. when enter floating point x takes decimal part of input , makes y value. unsure of mistake here.

#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 proper 'whole' number: " << endl;     }     return (x); }  int toobig() {     cout << "your number large, please enter smaller: " << endl;     int x = getint();     return (x); }  int toosmall() {     cout << "your number negative, please enter 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; } 

most conversions int stop find can't part of int , few conversion functions tell if stop before parsing whole string.

let's use one of few, shall we?

int getint() {     ( ; ; ) // loop until user provides can use.                  // dangerous. want give after while.     {         std::string input; // read in string         if (std::cin >> input)         {             char * endp; // updated pointer conversion stopped             errno = 0;              // convert string int             long rval  = std::strtol (input.c_str(), &endp, 10);              if (*endp == '\0') // check whole string 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                          // replace min , max own passed-in                           // min , max values if want                     {                         return rval; // return known-to-be-good int                     }                 }             }         }         else         { // note: when cin fails read string, it's over.            // time throw exception because            // shouldn't happen.             std::cin.clear(); // we'll clear error ,                                // enter infinite loop of failure         }         // failed reason. blow off user input , re-prompt         std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');         std::cout << "please input proper 'whole' number: " << std::endl;     }     return 0; // satisfy compiler because non-void function must return.                // never reached because of infinite loop. } 

Comments