3

谢谢大家回答我的第一个问题,但我还有一个问题。我这里有这个使用 strtol() 函数的代码。它可以工作,但问题是,如果我输入以下三个选项之一: (d 2) 它被视为一个字符串,如果 Input (2d) 它是一个字符串,并且 (d2) 是一个字符串。有没有办法检测数组中的数字?

  char userInput[256];
    char *end;
    printf("Please enter your name: ");
    scanf("%s", userInput);
    int userName = strtol(userInput, &end, 10);
    if (!*end)
    {
        printf("You have enter an int");
    }
    else
    {
        printf("You have entered a string");
    }
4

2 回答 2

1

如果您真的只需要检查字符串中是否包含数字,则可以:

int has_ints(char * str) {
    const int len = strlen(str);
    int i;
    for (i = 0; i < len; i++) {
        if (str[i] <= '9' && str[i] >= '0') {
            return 1;
        }
    }
    return 0;
}
于 2013-11-14T20:19:14.253 回答
0

我这样做了:)工作得非常漂亮!

    int exit = 0;
    int i;
    while (exit != 1)

    {

    char userInput[256] = {0};
    int asciiCode[256];
    int zeroCounter = 0;
    int letterProof = 0;
    int numberProof = 0;
    int specicalCharactersProof = 0;

    printf("\nPlease enter your name: ");
    fgets(userInput, 256, stdin);
    for (i = 0; i < 256; i++)
    {
        asciiCode[i] = userInput[i];

        if (asciiCode[i] == 0)
        {
            zeroCounter++;
        }
    }

    int reSize = (256 - zeroCounter);

    for (i = 0; i < reSize; i++)
    {
        if (asciiCode[i] >= '0' && asciiCode[i] <= '9')
        {

            numberProof = 1;
        }

        else if ((asciiCode[i] >= 'a' && asciiCode[i] <= 'z') || (asciiCode[i] >= 'A' && asciiCode[i] <= 'Z'))
        {

            letterProof = 1;
        }

        else if ((asciiCode[i] >= '!' && asciiCode[i] <= '/') || (asciiCode[i] >= ':' && asciiCode[i] <= '@') || (asciiCode[i] >= '[' && asciiCode[i] <= '`') || (asciiCode[i] >= '{' && asciiCode[i] <= '~'))
            {
                specicalCharactersProof = 3;
            }
    }
   if (letterProof == 1 && numberProof == 0 && specicalCharactersProof == 0)
   {
       printf("\nWelcome %s\n", userInput);
       exit = 1;
   }

   else
   {
       printf("\nInvalid Input.\n");
   }

    }

return(0);
}
于 2013-11-15T05:16:22.843 回答