将struct中的char-array与用户输入char-array进行比较

时间:2017-01-04 18:06:24

标签: c input struct compare c-strings

我正在编写一个代码来搜索文件中的特定学生,并计算它的平均值。一切都有效,除了一件事。当我在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

1 个答案:

答案 0 :(得分:0)

你无法比较C - &#34;字符串&#34; (实际上只是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的地址,而只是传递transport: { read: { url: "/api/Albums", // <-- Get data from here dataType: "json" // <-- The default was "jsonp" }, parameterMap: function (options, operation) { var paramMap = kendo.data.transports.odata.parameterMap(options); delete paramMap.$inlinecount; // <-- remove inlinecount parameter delete paramMap.$format; // <-- remove format parameter return paramMap; } },因为一个数组(`是^是)当传递给函数时,衰减到第一个元素的地址。

相关问题