[英]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.