【问题标题】:Comparing 2 strings and getting the error expected expression比较 2 个字符串并获得错误预期表达式
【发布时间】:2016-01-24 20:51:23
【问题描述】:

我正在开展一个项目,您可以在其中输入姓名并打印姓名首字母。当我尝试比较字符串时,出现“预期表达式”错误。我做错了什么?

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main(void) {
   printf("Name: ");
   string name = GetString();
   printf("\n");

   int length = strlen(name);
   string compair1 = " ";
   for(int l = 0;l<=length;l++) {
      char compair2 = name[l];
      int  res = strcmp(compair1,&compair2);
      if(res == 0) {
         printf("found blank space");
      }
   }
}

【问题讨论】:

  • for(int l = 0; name[l];l++) { if(name[l] == ' ') printf("found blank space\n"); }
  • 您不能只获取单个char 的地址并将其用作strcmp 的参数,因为它不是以空值结尾的。通常,这可能会导致分段违规。如果只想比较单个字符,可以使用int res = compair1[0] == compair2;
  • “int res = strcmp(compair1, &compair2);”中的作用和作用
  • @MarcusMardis &compair2 表示“compair2 的地址”。因此,您将 strcmp 传递给 char 变量的地址,而 strcmp 将其视为以空字符结尾的字符串的开头,而事实并非如此。
  • 你可以see here如何使用strcmp。

标签: c string compare cs50


【解决方案1】:
  • 如果你只是想找到空间,那么你可以这样做:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    int main(void)
    {
       printf("Name: ");
       char name[20];
       gets(name);
       printf("\n");
    
      int length = strlen(name);
      for(int l = 0;l < length;l++)
      {
          if(name[l] == ' ')
          printf("found blank space");
      }
    }
    

【讨论】:

  • 绝对正确。两个警告:1)gets() 不好。首选替代方案是fgets(mystring, len, stdin)。 2) 使用strchr() 将简化代码(并消除整个“for”循环)。 +1 NOT 使用 "cs50.h" ;)
  • @paulsm4:谢谢:)。
【解决方案2】:

您应该查找strtok()。这是一个给你的例子。

#include <string.h>
#include <stdio.h>

int main()
{
    char str[] = "Bufford T Justice";
    char *token;
    char space = ' ';
    int count = 0;

    token = strtok(str, &space);

    while( token != NULL ) 
    {
        printf( "%s\n", token );
        token = strtok(NULL, &space);
        if( token )
        {
            count++;
        }
    }

    printf("Number of spaces = %d\n", count);
    return(0);
}

从这个 sn-p 中,只需几行即可确定输入名称的首字母。

注意:如果您不希望字符串被strtok() 修改,您可以使用strchr() 并稍作改动。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多