-1

到目前为止,这是我的代码:

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

它工作正常,但我试图弄清楚如果用户输入任何不是数字的东西,如何让它循环。

当我按下一个字母或说出一个符号/符号时,密码就会中断。

4

3 回答 3

2

使用功能

isdigit() 

如果参数是十进制数字 (0–9),则此函数返回 true

不要忘记

#include <cctype>
于 2017-04-17T11:02:13.623 回答
1

我会使用std::getlineandstd::string来读取整行,然后只有当你可以将整行转换为双精度时才跳出循环。

#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;
}
于 2017-04-17T10:32:43.080 回答
1

这样做的一个好方法是将输入作为字符串。现在找到字符串的长度为:

int length = str.length(); 

确保包括stringcctype。现在,运行一个循环来检查整个字符串并查看是否有一个不是数字的字符。

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

如果任何字符不是数字,则 isInt 将为假。现在,如果您的输入(字符串)都是数字,请将其转换回整数,如下所示:

int integerForm = stoi(str); 

将 integerForm 存储在您的数组中。

于 2021-12-05T09:12:04.943 回答