c-当打印结构数组时,得到ascii符号,没有名称或值



我不确定这个问题是由我向结构中输入信息还是由我的打印例程产生的。

我的代码如下:

struct srecord {
char name[15];
int score;
};
void getAScore(struct srecord r, char name[], int scores){
strcpy(r.name,name);
r.score = scores;
}                                                                                                   
void getScores(struct srecord students[], int* num ){
printf("Enter number of students and then those students names and scores separated by a space.n");
scanf("%d", num);
int i;
char names[15];
int scores;
int j;
for(i = 0; i < *num; i++){
scanf("%s%d", names, &scores);
getAScore(students[i], names, scores);
}
}
void printAScore(struct srecord r){
printf("%s%dn", r.name, r.score );
}
void printScores(struct srecord r[],int num){
int i;
for(i = 0; i < num; i++){
printAScore(r[i]);
}
}

正如您所看到的,该结构由一个名称数组和score组成。我们在主类的数组中创建了10个这样的结构。

int main(){
struct srecord students[10]; // can handle up to 10 records
int num; // number of students
int average;
getScores(students, &num);
printScores(students, num);

我必须在终端中一次输入所有信息,然后完全相同地打印出来。

所以我输入了这样一个输入,第一行是学生人数,接下来的每一行都是一个名字,后面跟着一个分数,就像这样:

3
Tom 90
Jones 78
lawrence 8

然而,当我去打印它时,我会得到这个:

@0
0
0

我相信我的指针是正确的,但我认为信息被错误地放入了structs数组中?我一直在摆弄循环,但没有什么重要的改变,也没有什么真正有效的,所以我现在有点迷失了方向。我查阅了手册中的structs、printf和scanf,但对于可能的问题,我没有什么真正的答案,也没有其他关于这个主题的线索。

getAScore()需要接收一个指向该结构的指针,以便对其进行修改。否则,它将修改一个本地副本,该副本在函数返回时消失。

它还需要将名称复制到结构中。

void getAScore(struct srecord *r, char name[], int scores){                                                                                                                   strcpy(r.name,name);
r->score = scores;
strcpy(r->name, name);
}

然后将呼叫更改为:

getAScore(&students[i], names, scores);

最新更新