检查一个字符串在C中是否只有数字? [英] Check if a string has only numbers in C?

查看:12
本文介绍了检查一个字符串在C中是否只有数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的代码来检查字符串中是否只有数字.到目前为止它不起作用,任何帮助将不胜感激.

I'm trying to write a simple code to check if a string only has numbers in it. So far it's not working, any help would be appreciated.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
    char numbers[10];
    int i, correctNum = 0;

    scanf("%s", numbers);

    for(i = 0 ; i <= numbers ; ++i)
    {
        if(isalpha(numbers[i]))
        {
            correctNum = 1;
            break;
        }
    }

    if(correctNum == 1)
    {
        printf("That number has a char in it. FIX IT.
");
    }
    else
    {
        printf("All numbers. Good.
");
    }
    return 0;
}

推荐答案

除了其他答案,你也可以使用strtol 判断一个字符串是否全为数字.它基本上将字符串转换为整数,并忽略任何非整数.您可以阅读 手册页 了解有关此功能的更多信息,以及您可以使用它进行的广泛的错误检查.

Adding to the others answers, you can also use strtol to determine if a string has all numbers or not. It basically converts the string to an integer, and leaves out any non-integers. You can read the man page for more information on this function, and the extensive error checking you can do with it.

另外,你应该使用:

scanf("%9s", numbers);

代替:

scanf("%s", numbers);

为了避免缓冲区溢出.

下面是一些示例代码:

#include <stdio.h>
#include <stdlib.h>

#define MAXNUM 10
#define BASE 10

int main(void) {
    char numbers[MAXNUM];
    char *endptr;
    int number;

    printf("Enter string: ");
    scanf("%9s", numbers);

    number = strtol(numbers, &endptr, BASE);

    if (*endptr != '' || endptr == numbers) {
        printf("'%s' contains non-numbers
", numbers);
    } else {
        printf("'%s' gives %d, which has all numbers
", numbers, number);
    }

    return 0;
}

示例输入 1:

Enter string: 1234

输出:

'1234' gives 1234, which has all numbers

示例输入 2:

Enter string: 1234hello

输出:

'1234hello' contains non-numbers

这篇关于检查一个字符串在C中是否只有数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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