gpt4 book ai didi

c++ - 字符串 : Finding if the first word is repeated using strcmp

转载 作者:太空宇宙 更新时间:2023-11-04 14:01:57 27 4
gpt4 key购买 nike

我有一个作业,我必须输入要比较的名称数量。然后我要看看我打印的名字中是否重复了打印的名字。例如,如果我输入 5 Reagan, Bush, Reagan, Bush, Clinton,它会打印出“The first name was repeated”,但如果我输入 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;
}

最佳答案

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

    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。

关于c++ - 字符串 : Finding if the first word is repeated using strcmp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18950489/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com