简体   繁体   中英

How to make user input numbers only in C++?

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.

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;
}

Using the function

isdigit() 

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

Don't forget to

#include <cctype>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM