简体   繁体   English

如何存储然后水平打印 2d 字符/字符串数组 5 次?

[英]How to store and then print a 2d character/string array horizontally for 5 times?

I want to get 5 students' grades ( {"A+","A","A-"} like that) in an array for 3 subjects.我想在 3 个科目的数组中获得 5 个学生的成绩( {"A+","A","A-"}类的)。 How do I get user inputs and print them horizontally line by line in a table?如何获取用户输入并在表格中逐行水平打印? I have created code but it does not work.我已经创建了代码,但它不起作用。

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]);
    }
}

You could do something like this.你可以做这样的事情。 Make a struct that represents an "entry" of a database.制作一个表示数据库“条目”的结构。 Each entry contains a student name, and an array of grades depending on how many subjects they're taking.每个条目都包含一个学生姓名和一系列成绩,具体取决于他们所修科目的数量。

When you're using scanf() for strings, you'll want to scan for one less than the length of the array, in order to leave space for a null terminator.当您对字符串使用scanf()时,您需要扫描比数组长度少 1 的值,以便为空终止符留出空间。

You'll also need to flush stdin after each scanf() in case the user enters more than they're supposed to.您还需要在每次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;
}

Sample input/output:样本输入/输出:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM