如何在C中比较多个字符串

How to compare multiple strings in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun1(void);
void func1()
{
  printf("Function1 executed \n");
}
int main()
{
  char syscom[256];
  char check[] = "cmd";
  do 
  {
    printf("Enter function : ");
    fflush (stdout);
    scanf("%255s",syscom);
    int numb;
    numb = strcmp("funct1",syscom);
    printf("%d\n",numb);
    if (numb == 1)
    {
      func1();
    }
  }while(strcmp("quit",syscom) != 0);
  return 0;
}

出于某种原因,strcmp 在 do-while 循环中运行良好,但在实际循环中,您总是可以选择它 returns 1 的函数。例如在 Enter 函数部分,即使输入随机字符串,它也会像我希望的那样生成 1 而不是 0。我知道 c++ 会使该程序成为 breeze,但我希望它在 c.

所以我将标题设置为多个字符串,因为该程序将具有多个函数,这些没有包括在内,因为我不知道如何在多个函数上使用 strcmp。

改变这个:

numb = strcmp("funct1",syscom);
printf("%d\n",numb);
if (numb == 1) {
  func1();
}

对此:

numb = strcmp("funct1",syscom);
printf("%d\n",numb);
if (numb == 0) {
  func1();
}

下次post有问题请先看ref

returns an integral value indicating the relationship between the strings: return value indicates:

  1. <0 不匹配的第一个字符在 ptr1 中具有较低的值 比 ptr2
  2. 0 两个字符串的内容相等
  3. >0 第一个不匹配的字符在 ptr1 中的值大于 ptr2