这段代码出了什么问题?我如何找到有多少学生有相同的名字?
我如何找出所有名称拼写相同(重复((不能使用内置函数(。
输入:
Enter student name: Hasib
Enter student name: Hasib
Enter student name: Jhon
输出必须如下所示:
2 students have same name
代码:
#include <stdio.h>
struct student {
char name[20];
};
int main() {
struct student s[10];
int i, j, count = 0;
for (i = 0; i < 3; i++) {
printf("Enter student name: ");
gets(s[i].name);
}
for (i = 0; i < 3; i++) {
for (j = i + 1; j < 3; j++) {
if (s[i].name == s[j].name) {
count++;
}
}
}
printf("n%d students have same namenn", count);
}
存在多个问题:
-
C字符串不能像您那样与
==
进行比较。您只比较指针,而不是数组的内容。您必须包含<string.h>
并使用:if (strcmp(s[i].name, s[j].name) == 0) { /* duplicate name */ }
-
还要注意的是,不能使用
gets()
,因为如果输入太长,它可能会导致未定义的行为。事实上,攻击者可能会利用此漏洞执行任意代码。使用fgets()
或scanf("%19s", s[i].name)
。 -
为什么用10个条目定义
students
数组,而在main()
函数的其余部分只使用3?
这是一个修改后的版本:
#include <stdio.h>
#include <string.h>
struct student {
char name[20];
};
int main() {
struct student s[10];
int n, i, j, count;
for (n = 0; n < 10; n++) {
printf("Enter student name: ");
if (scanf("%19s%*[^n]", s[n].name) < 1)
break;
}
count = 0;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (strcmp(s[i].name, s[j].name) == 0) {
count++;
}
}
}
printf("n%d students have same namenn", count);
return 0;
}
编辑:您的计数方法对3个以上的条目不正确:如果4个学生具有相同的名称,则对0,1
、0,2
、0,3
、1,2
、1,3
和2,3
的count
将递增,因此有6个学生具有同一名称(!(。
以下是一个不使用strcmp()
的更正版本:
#include <stdio.h>
struct student {
char name[20];
};
int same_string(const char *s1, const char *s2) {
while (*s1 == *s2) {
if (*s1 == ' ')
return 1;
s1++;
s2++;
}
return 0;
}
int main() {
struct student s[10];
int n, i, j, count;
for (n = 0; n < 10; n++) {
printf("Enter student name: ");
if (scanf("%19s%*[^n]", s[n].name) < 1)
break;
}
count = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i != j && same_string(s[i].name, s[j].name)) {
count++;
break;
}
}
}
printf("n%d students have same namenn", count);
return 0;
}
请使用下面的代码,==不是一个用于字符串的工作命令,我们可以使用Strcmp进行同样的操作。
struct student
{
char name[20];
};
int main(){
struct student s[10];
int i,j=0,count,res;
for(i=0; i<3; i++)
{
printf("Enter student name: ");
gets(s[i].name);
}
for(i=0; i<3; i++)
{
for(j=i+1; j<3; j++)
{
if(strcmp(s[i].name, s[j].name)==0)
{
count++;
}
}
}
printf("n%d students have same namenn",count);
}
感谢