如何在C中检查字符串

Aff*_*mad -2 c string

我是C语言的新手.在下面的代码中,我正在检查输入值是否大于23或小于0,如果是,我再询问一个新值,但现在我想检查任何字符串值然后再次询问一个新值.

#include <stdio.h>

int main(void) {
  int h;

  printf("Value: ");
  scanf("%d", &h);
  while ((h < 0) || (h > 23)) {

    printf("Value: ");
    scanf("%d", &h);

  }
  printf("You pressed:%d\n", h);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 5

您需要使用读取整行fgets(),然后扫描该行sscanf(),或者您需要处理在scanf()被要求扫描数字时不愿意阅读过字母.

#include <stdio.h>

enum { MIN_VALUE = 0, MAX_VALUE = 23 };

int main(void)
{
    int h;
    char line[4096];
    while (fgets(line, sizeof(line), stdin) != 0)
    {
         if (sscanf(line, "%d", &h) == 1 && h >= MIN_VALUE && h <= MAX_VALUE)
         {
             printf("You entered: %d\n", h);
             break;
         }
         printf("What you entered was not a number between %d and %d\n",
                MIN_VALUE, MAX_VALUE);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果希望可接受的值为1..23,请将MIN_VALUE更改为1.

请注意,此代码使用的一个优点fgets()是您可以报告计算机读回用户的内容 - 代码不会这样做,但它可以非常容易.当您每行读取多个值时,这是最有价值的.如果scanf()读取预期的6个项目中的4个,则只有输入行的片段才能向用户报告.另一方面,如果sscanf()读取预期的6个项目中的4个,则可以报告用户输入的整行,这通常对用户更有意义.

或许这可能,但它会出现在第一个非整数数据上,而这些数据实际上并不符合规范:

#include <stdio.h>

int main(void)
{
    int h;
    while (scanf("%d", &h) == 1)
    {
         if (h >= 0 && h <= 23)
         {
             printf("You entered: %d\n", h);
             break;
         }
         printf("What you entered was not a number between 1 and 23\n");
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

或者,当scanf()失败时你可能需要吞下输入线的其余部分:

#include <stdio.h>

int main(void)
{
    int c, h;
    while (1)
    {
         switch (scanf("%d", &h))
         {
         case EOF:
             return 1;
         case 0:
             printf("What you entered was not a number between 1 and 23\n");
             while ((c = getchar()) != EOF && c != '\n') /* Gobble rest of line */
                 ;
             break;
         default:  /* or case 1: */
             if (h >= 0 && h <= 23)
             {
                 printf("You entered: %d\n", h);
                 return 0;
             }
             break;
         }
    }
    /*NOTREACHED*/
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

再想一想,使用fgets()版本; 它更清洁.