C 如何检查输入字符串是否由整数组成

C 如何检查输入字符串是否由整数组成,c,string,while-loop,C,String,While Loop,我试图做一个while循环,其中条件检查字符串的前四个元素不是整数。这是我的代码,不知怎的它不起作用。我尝试从ctype.h头使用isdigit函数 char tr_code[200]; char *endptr; scanf("%s", &tr_code); fd_code=strtol(tr_code,&endptr,10); while(strlen(tr_code)!=4 && isdigit(tr_code[0])==0 && isd

我试图做一个while循环,其中条件检查字符串的前四个元素不是整数。这是我的代码,不知怎的它不起作用。我尝试从ctype.h头使用isdigit函数

char tr_code[200];
char *endptr;

scanf("%s", &tr_code);
fd_code=strtol(tr_code,&endptr,10);

while(strlen(tr_code)!=4 && isdigit(tr_code[0])==0 && isdigit(tr_code[1])==0 && isdigit(tr_code[2])==0 && isdigit(tr_code[3])==0)
{
    printf("\nInvalid Code. please enter another '4-digit' Code: ");
    scanf("%s", &tr_code);
    fd_code=strtol(tr_code,&endptr,10);
}

IIRC“scanf”签名返回一个整数,即终端读取的字符数。

您正在使用
&&
,但
|
是您应该使用的:

while(strlen(tr_code) != 4 || !isdigit(tr_code[0]) || !isdigit(tr_code[1]) || !isdigit(tr_code[2]) || !isdigit(tr_code[3]))

使用
&&&
,任何四个字符长的输入,或在前四个位置中的任何一个位置都有一个数字(即使该内存是上次输入的剩余内存,因为字符串可能更短)都将通过。

它是如何工作的?症状是什么?以什么方式不起作用?你期望什么,实际发生了什么?我期望如果输入不是整数,循环会继续。我不只是将输入类型设为整数,因为稍后需要字符串变量