我如何遍历字符串中的所有字符并检查它们是否都是C中的数字?

问题描述 投票:-1回答:2

我正在尝试找出一种检查字符串中所有字符的方法。在网上搜索后,我发现我可以创建一个函数来执行此操作,但是由于某种原因,即使它非常简单,也无法正常工作。这是我的代码:

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

struct id{
    char id_num[10];
};

int isNumber(char p[])
{
    int i;
    for(i=0; i<strlen(p); i++){
        if(isdigit(p[i])){
            return 0;
        }
        else return 1;
    }
}


void read(struct id s)
{
    int len1;
    do{ 
        printf("Give id number: ");
        scanf("%s", s.id_num);
        len1 = strlen(s.id_num);
    } while(len1 < 0 || len1 > 10 || isNumber(s.id_num) == 1);
}

int main(void)
{
    struct id a;
    read(a);
}

[如果您想知道为什么将id_num设为char字符串,是因为我需要将数字从0到10个字符。另外,该代码不会出现任何错误,但是会占用我输入的任何内容。例如,它接受不应接受的“ 5555tt”。我做错了什么?预先谢谢你。

c string function numbers
2个回答
0
投票

在for循环中,找到数字后退出。因此,如果第一个字符为5,则退出循环。您需要检查所有元素,如果不是数字,则返回1

int isNumber(char p[])
{
    int i;
    for(i=0; i<strlen(p); i++){
        if(!isdigit(p[i])){
            return 1;
        }
        else return 0;
    }
}

也功能read需要通过地址获取参数。 void read(struct id *s)

void read(struct id *s)
{
    int len1;
    do{ 
        printf("Give id number: ");
        scanf("%s", s->id_num);
        len1 = strlen(s->id_num);
    } while((len1 < 0) || (len1 > 10) || (isNumber(s->id_num) == 1));
}

0
投票

对于初学者,功能read应通过引用接受其参数,例如

void read(struct id *s);

否则,其论点就没有意义。

isNumber函数非常简单。

int isNumber( const char p[] ) 
{
    const char *s = p;
    while ( isdigit( ( unsigned char )*s ) ) ++s;

    return  p[0] != '\0' && *s == '\0';
}

这里是演示程序。

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

int isNumber( const char p[] ) 
{
    const char *s = p;
    while ( isdigit( ( unsigned char )*s ) ) ++s;

    return  p[0] != '\0' && *s == '\0';
}

int main(void) 
{
    printf( "Is a number - %s\n", isNumber( "" ) ? "true" : "false"  );
    printf( "Is a number - %s\n", isNumber( "A" ) ? "true" : "false"  );
    printf( "Is a number - %s\n", isNumber( "12A" ) ? "true" : "false"  );
    printf( "Is a number - %s\n", isNumber( "123" ) ? "true" : "false"  );

    return 0;
}

其输出为

Is a number - false
Is a number - false
Is a number - false
Is a number - true
© www.soinside.com 2019 - 2024. All rights reserved.