scy*_*120 1 c arrays string structure
当我尝试编译我的程序时,我在标题中收到警告消息,当我在扫描名称和分数后运行它时它就停止了.我在练习使用字符串时遇到过这个问题很多次,但我找不到解决方案.
#include <stdio.h>
struct students {
char name[20];
int score[20];
} student;
int main() {
int i, n;
printf("Number of students:\n");
scanf("%d", &n);
for(i=0; i<n; i++) {
printf("Name of the student:\n");
scanf("%s", &student.name[i]);
printf("Score of the student:\n");
scanf("%d", &student.score[i]);
}
for(i=0;i<n;i++) {
if(student.score[i] >= 15) {
printf("%s passed the exam\n", student.name[i]); }
else {
printf("%s failed the exam\n", student.name[i]);
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有几个问题:
printf("%s passed the exam\n", student.name[i]);
Run Code Online (Sandbox Code Playgroud)
student.name[i]是一个char但%s格式说明符需要指针char.
但实际问题是你的学生申报不是你所需要的.以下结构声明一名学生,其姓名最长可达19个字符,并且有20个分数.
struct students {
char name[20];
int score[20];
} student;
Run Code Online (Sandbox Code Playgroud)
但你需要20个(或更多?)学生,每个学生都有一个分数:
struct student {
char name[50]; // name up to 49 characters
int score; // score
} student;
struct student students[20]; // array of 20 students
Run Code Online (Sandbox Code Playgroud)
Il将代码的实现作为练习留给读者.您需要熟悉以下概念:
scanf和的基础知识printf所有这些主题都在C课本中介绍.