我正在编写一段代码来搜索文件中的特定学生,并计算其平均值。除了一件事之外,一切都有效。当我在 char 变量中输入学生的姓名时,要在文件中搜索他,编译器不会得到它等于文件结构中的 char ...
#include <stdio.h>
#include <stdlib.h>
#define nl printf("\n")
#define N 100
struct student {
char id[N][N];
int vote[10][10];
};
int main()
{
struct student stud;
FILE *filer;
int i=0, j=0, k=0, n_stud=0;
char checker[1], who[N];
float avg[10], mark=0.0, count=0.0;
printf("Introduce student id: ");
scanf("%14s", &who);
printf("Searching for student %s...\n", who);
nl;
filer=fopen("students.dat", "r");
if(filer==NULL) {
printf("Can't open file...\n");
}
for(i=0; fscanf(filer, "%s", &stud.id[i])!=NULL && fscanf(filer, "%c", &checker)!=EOF; ++i) {
for(j=0; fscanf(filer, " %d", &stud.vote[i][j])!=-1; ++j ) {
if(stud.vote[i][j]!=-1) {
mark=mark+stud.vote[i][j];
count++;
} else {
for(k=j; k<10; k++) {
stud.vote[i][k]=0;
}
break;
}
}
n_stud++;
avg[i]=mark/count;
mark=0.0; count=0.0;
}
for(i=0; i<n_stud; ++i){
if (who == stud.id[i]) { //HERE IS THE PROBLEM!!!
printf("Student %s's average is: %.2f", stud.id, avg[i]);
}
}
nl;
fclose(filer);
return EXIT_SUCCESS;
}
文件
s11111 30 28 18 -1
sa44er44 23 18 30 18 29 18 29 -1
s33333 30 30 -1
22222idx 18 -1
最佳答案
您无法使用 ==
运算符来比较 C-“字符串”(实际上只是 char
数组):
if(who==stud.id[i]){
使用strcmp()
function相反:
if (strcmp(who, stud.id[i]) == 0) {
<小时/>
不相关,但仍然很重要:您要确保不让用户溢出 who
。
您可以通过告诉 scanf()
who
的大小来做到这一点,如下所示:
scanf("%14s", who); /* Tell it one less to have a spare char
to store the '0'-terminator. */
虽然 scanf(()
通常需要一个地址作为参数,但您不会传递 who
的地址,而只传递 who
,因为数组(“who^”)在传递给函数时会衰减到其第一个元素的地址。
关于将结构体中的字符数组与用户输入的字符数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41470461/