【问题标题】:How to make user input numbers only in C++?如何仅在 C++ 中使用户输入数字?
【发布时间】:2017-04-17 10:19:14
【问题描述】:

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

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

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

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

【问题讨论】:

标签: c++ input numbers numeric-limits


【解决方案1】:

使用函数

isdigit() 

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

别忘了

#include <cctype>

【讨论】:

    【解决方案2】:

    我会使用std::getlinestd::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;
    }
    

    【讨论】:

    • 这可能没问题,但有点不对称,因为它接受/忽略数字之前的空格但不接受数字之后的空格。如果重要的话,你可以使用ss &gt;&gt; d &gt;&gt; std::skipws(和#include &lt;iomanip&gt;)在两端允许空格。
    【解决方案3】:

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

    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 存储在您的数组中。

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      相关资源
      最近更新 更多