1

我有一个任务,我必须输入我想比较的名字的数量。然后我必须查看打印的名字是否在我打印的名称中重复。例如,如果我输入 5 Reagan, Bush, Reagan, Bush, Clinton,它会打印出“名字被重复”,但如果我输入 Davis 代表任何一个里根,它会拒绝。我尝试了 for 循环和 if 语句,但似乎找不到正确的输出。我正在使用 Dev C++,这就是我目前所拥有的。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
    char curname[30], firstname[30];
    int num, i, freq = 1;


    printf("How many names do you want to enter?\n");
    scanf("%d", &num);
    printf("What is the first name?");
    scanf("%s", firstname); 
    printf("Enter each of their names.\n");
    for (i=0; i<num; i++) {

        scanf("%s", curname);

        if (i==0) {
          strcmp(curname, firstname) != 0;
          printf("The first name in the list was repeated.\n"); 
        }
        else if (strcmp(curname, firstname) == 1)
          printf("The first name in the list was not repeated.\n"); 
    }
    system("pause");
    return 0;
}
4

4 回答 4

0

您必须比较名称,strcmpi 更合适(不区分大小写的比较)

 if (strcmpi(curname, firstname)==0)
    printf("The first name in the list was repeated.\n"); 
 else 
    printf("The first name in the list was not repeated.\n"); 
于 2013-09-23T02:02:36.420 回答
0

strcmp返回值可能大于 0 或小于 0,因此:

strcmp(curname, firstname) == 1

改成:

strcmp(curname, firstname) != 0

其他:您没有将姓名记录到列表中,因此如果姓名不重复,您将无法找到姓名。

于 2013-09-23T01:49:01.787 回答
0

所以我根据建议编辑了我的程序。这就是我现在所拥有的。如果名称作为最后一个值输入,它只会给我正确的输出。太感谢了!!:)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char curname[30], firstname[30];
int num, i, freq = 1;

// Read in the number of students.
printf("How many names do you want to enter?\n");
scanf("%d", &num);
printf("What is the first name?\n");
scanf("%s", firstname); 
printf("Enter each of their names.\n");
for (i=0; i<num; i++) 

// Read the current name.
scanf("%s", curname);

// Always update the best seen for the first name.
if (strcmp(firstname, curname)== 0)  {
    printf("The first name in the list was repeated.\n"); }
 else
    printf("The first name in the list was not repeated.\n"); 
    system("pause");
    return 0;
}
于 2013-09-23T14:29:54.483 回答
0

您只需要进行一次比较并根据该比较的结果打印您的消息。

    if (strcmp(curname, firstname) == 0 ) {
      printf("The first name in the list was repeated.\n"); 
    }
    else {
      printf("The first name in the list was not repeated.\n"); 
    }

非常清楚任何函数调用的返回值是什么总是值得的,在这种情况下是 strcmp。

于 2013-09-23T01:39:42.283 回答