【问题标题】:using strncmp for selection in string使用 strncmp 在字符串中进行选择
【发布时间】:2015-07-07 20:03:33
【问题描述】:

我是 C 代码的新手。对于此特定代码,如果用户输入名称

约翰,

"john is cool" 将被打印出来。我认为我没有正确使用strncmp()。 有人可以帮忙吗?

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

int main(){
char namedata[50], names;


int counter = 0, n;


printf("Enter Number of family members being enter into program \n");
scanf("%d", &n);

for (names=0; names<n; ++names)
{

printf("Enter family member name:\n");
scanf("%s",namedata);
counter = counter +1;
printf("name:");
puts(namedata);

}
if (strncmp (name,"john") == 0)
{
  printf ("found %s\n",name);
}


return 0;   
}

【问题讨论】:

  • strncmp 接受three 参数
  • 通常给变量加 1,如下所示:counter++;
  • 如果要读入多个字符串,需要有一个二维字符数组:char namedata[50][50];。这个可以容纳 50 个长度为 49 的字符串,每个字符串有一个结束零字符 (\0)。
  • @Pynchia 评论中的“三”字是hyperlink

标签: c arrays string strcmp


【解决方案1】:

您在这里遇到了一个逻辑问题。你只有一个名为

的数组
char namedata[50]

为此,您将采用 n 输入,每个输入都会覆盖前一个。因此,只保留最后一个输入。如果你想要一个“名字”的数组,你需要使用一个二维数组来存储所有的名字,类似于

char namedata[50][50];

scanf("%49s",namedata[names]);

并且比较也应该在同一个范围循环中完成,以检查数组中的每个值。

也就是说,

  1. strncpy 的用法错误。有关正确用法,请参见手册页。
  2. scanf("%s",namedata); 对于缓冲区溢出可能不安全。至少,使用scanf("%49s",namedata); 来避免更长的输入溢出。
  3. main() 的推荐签名是int main(void)

【讨论】:

  • prog.c:18:23: error: 'name' undeclared (first use in this function) scanf("%49s",namedata[name]);我更改了所有内容,但在 Ideone.com 上不断收到该错误
  • @MikeR 哎呀,应该是names,但这真的是你应该让我解决的问题吗? :-)
  • 是的,我看到我的错误仍然抛出这些错误 prog.c:18:1: 警告:数组下标的类型为 'char' [-Wchar-subscripts] scanf("%49s",namedata [名称]); prog.c:23:26: 错误: 宏 "strncmp" 需要 3 个参数,但如果 (strncmp (names,"john") == 0) prog.c:23:28: 警告:比较总是如果 (strncmp (names,,"john") == 0) ^
  • @MikeR 这些错误已经够详细了。将 char names 更改为 int names 并再次阅读我的答案以修复这些错误。
【解决方案2】:

至少做到:

for (names=0; names<n; ++names) {
 printf("Enter family member name:\n");
 scanf("%s",namedata);
 counter++; // don't know what this is used for
 printf("name:");
 puts(namedata);
 if (strncmp(name,"john", 4) == 0) { // strncmp takes three arguments
  printf ("found %s\n",name);
  break; // exit the loop maybe?
 }
}

但是,如果您希望程序收集所有名称,然后查找名为 john 的名称,则需要将给定名称存储在它们自己的区域中,如前面的答案所述。 为此,您需要一个指向 char 的指针数组并学习如何分配/释放内存。

玩得开心! :)

【讨论】:

    【解决方案3】:

    我明白了,谢谢

    #include <stdio.h>
    #include <string.h>
    
    int main(){
    char namedata[50];
    
    int n, names;
    printf("Enter Number of family members being enter into program \n");
    scanf("%d", &n);
        for (names=0; names<n; ++names)
        {
    
        printf("Enter family member name:\n");
        scanf("%s", &namedata);
        printf("name:");
        puts(namedata);
    
        }
            if (strcmp(namedata,"crystal")==0)
            {
             printf("crsytal is cool");
             }
    return 0;   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 2013-11-03
      相关资源
      最近更新 更多