-1

So far, this is my code:

while(bet > remaining_money || bet < 100)
    {
        cout << "You may not bet lower than 100 or more than your current money. Characters are not accepted." << endl;
        cout << "Please bet again: ";
        cin >> bet;
    }

It works fine but I'm trying to figure out how to make it loop if the user inputs anything that isn't a number as well.

When I press a letter or say a symbol/sign, the code just breaks.

  • Possible duplicate of [How to handle wrong data type input](http://stackoverflow.com/questions/10349857/how-to-handle-wrong-data-type-input) – Fureeish Apr 17 '17 at 10:43

3 Answers3

2

Using the function

isdigit() 

This function returns true if the argument is a decimal digit (0–9)

Don't forget to

#include <cctype>
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

I would use std::getline and std::string to read the whole line and then only break out of the loop when you can convert the entire line to a double.

#include <string>
#include <sstream>

int main()
{
    std::string line;
    double d;
    while (std::getline(std::cin, line))
    {
        std::stringstream ss(line);
        if (ss >> d)
        {
            if (ss.eof())
            {   // Success
                break;
            }
        }
        std::cout << "Error!" << std::endl;
    }
    std::cout << "Finally: " << d << std::endl;
}
  • That's probably fine, but a bit asymmetric in that it accepts/ignores whitespace before the number but not after. You could use `ss >> d >> std::skipws` (and `#include `) to allow whitespace at either end, if it mattered. – Tony Delroy Apr 17 '17 at 10:42
1

A good way of doing this is to take the input as a string. Now find the length of the string as:

int length = str.length(); 

Make sure to include string and cctype. Now, run a loop that checks the whole string and sees if there is a character that is not a digit.

bool isInt = true; 
for (int i = 0; i < length; i++) {
        if(!isdigit(str[i]))
        isInt = false; 
    }

If any character is not a digit, isInt will be false. Now, if your input(a string) is all digits, convert it back to an integer as:

int integerForm = stoi(str); 

Store integerForm in your array.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Syed Nouman
  • 53
  • 1
  • 9