【问题标题】:how to check a user given string? [duplicate]如何检查用户给定的字符串? [复制]
【发布时间】:2021-08-17 14:18:29
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

int main()
{
  char *s = (char*)malloc(sizeof(char)*5);
  printf("Enter:");
  scanf("%5s",s); //s == abcde

  if(s == "abcde")
  printf("Yes");
  else
  printf("NO");
  
  return 0;
}

我想检查用户给定的输入,如上所述。但它总是将输出显示为“否”。我做错了什么?

【问题讨论】:

  • OT:s 需要 6 个字符,空终止符需要多一个字符。但是无论如何分配固定数量的内存是毫无意义的,您也可以拥有char s[6];

标签: c string pointers


【解决方案1】:

string.h 中有很多函数可以做到这一点。

最常见的是strcmp()

int strcmp(const char *s1, const char *s2).

如果s1s2 相同,则strcmp() 应返回0。

  if(strcmp(s, "abcde") == 0)
    printf("Yes");

还有strncmp(),如果你想比较s1的最多n字节与s2

您的malloc() 调用错误,您需要一个额外的字节来处理\0。 您也可以跳过sizeof(char),因为它保证为1,以及you don't have to type cast the result of malloc

char *s = malloc(5 + 1);

【讨论】:

    【解决方案2】:

    您可以使用 string.h 中的 strcmp

    #include <stdio.h>
    #include <stdlib.h>
    #include<string.h>
    
    int main()
    {
      char *s = (char*)malloc(sizeof(char)*5);
      printf("Enter:");
      scanf("%5s",s); //s == abcde
    
      if(strcmp(s, "abcde") == 0)
        printf("Yes");
      else
        printf("NO");
      
      return 0;
    }
    

    【讨论】:

    • 另外:他没有为s分配足够的空间。
    猜你喜欢
    • 2015-01-22
    • 2011-07-05
    • 2015-09-11
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 2011-02-16
    相关资源
    最近更新 更多