加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何查看输入的值是否为数字而不是字符?

发布时间:2020-12-16 10:14:27 所属栏目:百科 来源:网络整理
导读:我想知道是否有人输入了一个号码,如果他们这样做,程序会继续,但如果他们没有,程序就会终止. int main(void) { int i; printf("Enter a number: "); scanf("%d",i); /*If input is not a number than terminate*/ /*Otherwise continue*/ else { if (test_pri
我想知道是否有人输入了一个号码,如果他们这样做,程序会继续,但如果他们没有,程序就会终止.

int main(void) {
    int i;

    printf("Enter a number: ");
    scanf("%d",&i);
    /*If input is not a number than terminate*/


    /*Otherwise continue*/
    else {
        if (test_prime(i))
            printf("Prime.n");
        else
            printf("Not prime.n");
    }
    return 0;
}

如果用户输入“hello”而不是我希望程序终止.

解决方法

那么正确的做法就是这样

int main(void) {
    int i;

    printf("Enter a number: ");
    if( scanf("%d",&i) != 1){
        fprintf(stderr,"%sn","Error in input,input is not number");
        exit(1);
    }
    /*input is a number */

    if (test_prime(i))
       printf("%sn","Prime.");
    else
       printf("%sn","Not prime.");

    return 0;
}

检查scanf的返回值将帮助我们了解scanf调用是否成功.

或者,您可以使用fgets()获取行输入,然后解析它并检查strtol等函数.
检查输入是否正确,仅对其应用isdigit()不是解决方案.(如其他答案中所提供).你可以通过输入1234进行检查,你会看到isdigit()解决方案在这里失败,尽管它不应该.

为了让您了解为什么isdigit解决方案不起作用,从7.4.1.5标准我们可以看到引用

The isdigit function tests for any decimal-digit character.

十进制数字符是0,1 … 9.

提供的解决方案说明:

如果你查看它所说的函数的返回值

the function returns the number of input items assigned,which can be
fewer than provided for,or even zero,in the event of an early
matching failure.

这是正在检查的内容.这也适用于多位数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读