仅数字 [英] only digit

查看:80
本文介绍了仅数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了代码,如果用户输入任何
,我只需要输入数字
其他字符或符号将显示此消息

您输入的数字不是数字再试一次"

我写的代码先检查第一个数字,然后输入

无限循环 我要检查数字是否为数字,然后继续执行其他操作

再次输入数字


例如:

I''ve been written code i need to enter only digit if the user enter any

thing else char or symbols this message will be shown

"your enter is not digit try again"

the code I''ve been written it check the first number then entered an

infinite loop i want to check if digit then continue else

enter the number again


for example:

int id;

start:
    cout<<"Enter Your id: ";
    cin>>id;
    if  (isdigit(id))
    {
        if (1>id)
        {
            cout<<"Your id is wrong.. "<<endl;
            goto start;
        }
        else if (id>32787)
        {
            cout<<"Your id is wrong.. "<<endl;
            goto start;
        }
        else
        {
            cout<<"Your id must be digit"<<endl;
            goto start;
        }
    }



这是否检查数字是否如其定义(int在+ -32787之间)

我正在使用Borland c ++

在此先感谢
希望您能帮忙



this if to check if the number as it definition (int is between +-32787)

i am using Borland c++

thanks in advance
i hope you can help

推荐答案



您可以简单地检查输入内容是否为有效的unsigned int,例如:
Hi,

You may simply check that input is a valid unsigned int and nothing else, for instance:
#include <iostream>
#include <limits>

using std::cin;
using std::cout;
using std::endl;

unsigned int IdInput()
{
    unsigned int id = 0;
    for(;;)
    {
        cout  <<"Enter Your id: ";
        cin >> id;
        cin.clear();
        cin.ignore(std::numeric_limits<int>::max(), '\n');
        if (cin.gcount() != 1)
            cout<<"Your id must be digit"<< endl;
        else if (!id || (id > 32787))
            cout << "Your id is wrong.. " << endl;
        else
            return id;
    }
}

int main()
{
    cout << "Valid id : " << IdInput() << endl;
}



编辑代码以处理以非数字开头的输入.

欢呼声,
AR



Code edited to handle input beginning with a non-digit.

cheers,
AR


首先要学习的是如何格式化代码,使其清晰易读.现在,我已经为您完成了任务,我想您可以看到它为什么处于循环状态.
The first thing to learn is how to format your code so it is clearly readable. Now that I have done it for you I guess you can see why it is in a loop.


我正在尝试您可以看到此信息

i am trying you can see this

<pre />
int read(){
  
   int id;     
    
   for (int i=1; i<4 ;i++)
     {
          cout<<"Enter Your id: ";
          cin>>id;
         
     if (isdigit(id))
            
         if ((id>1) && (id<32787))
              {
              return id;
              }
            
         else
             {
              cout<<"Your id is wrong.. "<<endl;
              cout<<"Try again"<<endl;
             }
    else
        {
 cout<<"Your id is wrong must be digit.. "<<endl;
cout<<"You are Trying to Enter Your id number "<<i<<" times incorrect You have only 3 Times"<<endl;
        continue;
     }
}
}


这篇关于仅数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆