0

I create do-while loop that checking input value (below). Only value let to out this loop is 1 and 2. When I put double value ex. 1.2 or 4.5 it's implicit conversion to integer (1 and 4 value). When I put string value, the loop working infinity and I have to close console and debug from the beginning. How can I write correct loop that protect input value from double and string value?

int triangle;
do{
        cout << "Put the number (1 or 2): ";
        cin >> triangle;
    } while (triangle > 2 || triangle < 1 || !cin);
kenzolek
  • 344
  • 6
  • 24
  • loop condition should be `cin && (triangle < 1 || triangle > 2)`. – M.M May 27 '16 at 09:57
  • The accepted answer in [this thread](http://stackoverflow.com/questions/10178830/input-validation-for-numeric-input) is what you're looking for. You can tweak it to read a float and check for decimal part. – jrok May 27 '16 at 09:57
  • See [fmod](http://en.cppreference.com/w/cpp/numeric/math/modf). – jrok May 27 '16 at 10:03

4 Answers4

2
int check()
{
    string s;
    cin >> s;
    if(s.length() == 1)
    {
        if((s[0] == '1') || (s[0] == '2'))
        {
            return s[0] - '0';
        }
    }
    return 0;
}
int main()
{
    int triangle;
    do
    {
        cout << "Put the number (1 or 2): ";
    }
    while (triangle = check());
    return 0;
}
sameerkn
  • 2,209
  • 1
  • 12
  • 13
1

You can check it by doing the follorwing

int triangle;
cin >> triangle;

if (cin.fail()) {
    //Not an int.
}
1

1.It's better to initialize triangle.

2.When std::basic_istream::operator>> extraction fails, failbit will be set. You should check the result and call std::basic_ios::clear to clear error state and std::basic_istream::ignore to skip bad inputs.

int triangle = 0;

for (;;) {
    cout << "Put the number (1 or 2): ";
    if (cin >> triangle) {
        if (triangle == 1 || triangle == 2) break;
    } else {
        cin.clear(); // reset stream state after failure
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
    }
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Yes, this solution is solve issue with enter string value but problem with double value is still exist. Expecially when I put ex. '1.2' it is implicity conversion to '1' and let it to out loop. – kenzolek May 27 '16 at 09:50
  • @kenzolek For `int`, the input process (extraction) will end at char `.`, then only read `1` for it. I think you need to change type to `string`, and then check it's an `int` or `double` or something else. – songyuanyao May 27 '16 at 10:02
-2

scanf("%d", &triangle) return 1 if it read one integer else 0.

So you can do it like this (It also takes care of EOF)

printf("Enter option (1 or 2)\n");
while(~scanf("%d", &n))
{
     if (n!=1 && n!=2)
           break;
     printf("Enter option (1 or 2)\n");
}
Hello
  • 5