【问题标题】:Checking for letters when reading an integer读取整数时检查字母
【发布时间】:2015-08-23 08:35:20
【问题描述】:

我正在制作一个需要用户输入生产订单(长 7 位)的应用,如下所示:

int order = 0;
cout << "Insert the order number: ";
cin >> ordem;

如何防止用户输入字母?喜欢“I2345G789”吗?

这样做,我的应用程序将进入无限循环。我正在考虑使用这样的功能:

bool isLetter(int a)
{
    string s = to_string(a);
    for (int i = 0; i < s.size()-1; i++)
    {
        if (isdigit(s[i]))
        {
            return false;
        }
        else
            return true;
    }       
}

然后:

if (isLetter(order))
{
    cout << "Insert only numbers \n";
}

但它不起作用。为什么?以及如何改进代码?

PS:我对编程很陌生,所以,对于初学者的任何错误,我深表歉意。

【问题讨论】:

  • @Wimmel 这提供了一个不同的 解决方案,但不会帮助 OP 理解他最初的错误。我不会将此标记为重复。
  • 为什么要否决我的问题?你们太严格了,拜托!菜鸟怎么会这样学..

标签: c++ windows c++11 type-conversion


【解决方案1】:

我猜你的代码有一个循环,以便再次询问订单号,以防它包含非数字,例如:

while(...)
{
    int order = 0;
    cout << "Insert the order number: ";
    cin >> order;
}

如果您输入的内容无法解析为整数,则输入流将进入故障模式,这可能是您最终陷入无限循环的原因。为了以简单的方式解决您的问题,您可以改为读取字符串:

string order;
while (true)
{
    cout << "Insert the order number: ";
    cin >> order;

    if (isLetter(order))
        cout << "Insert only numbers" << endl;
    else
        break;
}

函数isLetter() 现在接受一个字符串,如下所示:

bool isLetter(string s)
{
    // Return true if the given string contains at least one letter.
    for (size_t i = 0; i < s.size(); i++)
        if (!isdigit(s[i]))
            return true;

    // Return false if there are only digits in the given string.
    return false;
}

请注意,它应该是i &lt; s.size() 而不是i &lt; s.size()-1。也许您应该将函数 isLetter() 重命名为 hasLetter(),因为这样会更正确。

【讨论】:

  • 好答案!我假设 i &lt; s.size() - 1 是错误的?因为在我看来,这会阻止我获得最终的字符,即 '\0'
  • 函数size()在计算字符时不包括\0。如果一个字符串是 abc,那么它的长度(大小)是 3 而不是 4,即使附加了 \0 以正确终止该字符串。
  • 很好,我不知道。再次感谢您!
  • 现在我要问你:为什么你使用size_t i 而不仅仅是int
  • 函数size()返回类型size_t。如今,这通常是一个无符号的 64 位整数。如果您只使用int,那么您的编译器应该会给您一个警告(如果您打开警告),您正在将有符号类型与无符号类型进行比较。此外,int 通常只有 32 位。因此,对于非常大的结构,您可能会溢出。但是,unsigned int 也适合您的用例;)
猜你喜欢
  • 2014-07-25
  • 2011-09-01
  • 1970-01-01
  • 2018-06-19
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
  • 2016-01-03
相关资源
最近更新 更多