字符串:使用strcmp查找是否重复第一个单词

时间:2013-09-23 01:17:33

标签: c++ string strcmp

我有一项任务,我必须输入我想要比较的名字数量。然后我必须看看打印的名字是否在我打印的名字中重复。例如,如果我放入5里根,布什,里根,布什,克林顿,它将打印出“第一个名字被重复”,但如果我把任何一个里根放入戴维斯,它就会拒绝。我尝试过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 个答案:

答案 0 :(得分: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。

答案 1 :(得分:0)

strcmp返回值可能大于0或小于0,所以:

strcmp(curname, firstname) == 1

更改为:

strcmp(curname, firstname) != 0

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

答案 2 :(得分: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"); 

答案 3 :(得分: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;
}