[英]How to store and then print a 2d character/string array horizontally for 5 times?
我想在 3 个科目的数组中获得 5 个学生的成绩( {"A+","A","A-"}
类的)。 如何获取用户输入并在表格中逐行水平打印? 我已经创建了代码,但它不起作用。
student[i]=row,
subject[j]=colomn
while(j<5){
for(i=0; i<n; i++){
scanf("%3s",name[i]);
}
}
// dispaying strings
printf("\nEntered names are:\n");
while(j<3){
for(i=0;i<n;i++){
puts(name[i]);
}
}
你可以做这样的事情。 制作一个表示数据库“条目”的结构。 每个条目都包含一个学生姓名和一系列成绩,具体取决于他们所修科目的数量。
当您对字符串使用scanf()
时,您需要扫描比数组长度少 1 的值,以便为空终止符留出空间。
您还需要在每次scanf()
之后刷新标准输入,以防用户输入的内容超出预期。
#include <stdio.h>
#define NUM_STUDS 3
#define NUM_SUBJS 2
struct entry {
char name[10];
char grade[NUM_SUBJS][3];
};
struct entry entries[NUM_STUDS];
int main(void) {
int i, j, c;
/* Collect student names */
for(i=0; i<NUM_STUDS; i++) {
printf("Enter student name %d/%d: ", i+1, NUM_STUDS);
scanf("%9s", entries[i].name);
while ((c = fgetc(stdin)) != '\n' && c != EOF); /* Flush stdin */
}
/* Collect grades */
for(i=0; i<NUM_STUDS; i++) {
printf("Enter %d grades for %s: ", NUM_SUBJS, entries[i].name);
for(j=0; j<NUM_SUBJS; j++) {
scanf("%2s", entries[i].grade[j]);
while ((c = fgetc(stdin)) != '\n' && c != EOF); /* Flush stdin */
}
}
/* Print out table of results */
printf("Results:\n");
for(i=0; i<NUM_STUDS; i++) {
printf("%-10s: ", entries[i].name);
for(j=0; j<NUM_SUBJS; j++) {
printf("%-3s", entries[i].grade[j]);
}
printf("\n");
}
return 0;
}
样本输入/输出:
Enter student name 1/3: Bob
Enter student name 2/3: Alice
Enter student name 3/3: Joe
Enter 2 grades for Bob: B+
A
Enter 2 grades for Alice: A-
C
Enter 2 grades for Joe: D-
E
Results:
Bob : B+ A
Alice : A- C
Joe : D- E
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.