如何存储并水平打印一个二维字符/字符串数组5次?

问题描述 投票:0回答:1

我想获得 3 个科目的 5 个学生的成绩(

{"A+","A","A-"}
这样)。如何获取用户输入并在表格中逐行水平打印它们?我已经创建了代码,但它不起作用。

student[i]=row,  
subject[j]=column

while(j<5){
    for(i=0; i<n; i++){
        scanf("%3s",name[i]);
    }
}
// displaying strings
printf("\nEntered names are:\n");
while(j<3){
    for(i=0;i<n;i++){
        puts(name[i]);
    }
}
c
1个回答
1
投票

你可以做这样的事情。 创建一个代表数据库“条目”的结构。 每个条目都包含一个学生姓名和一系列成绩,具体取决于他们选修的科目数。

当您对字符串使用

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  
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.