Search code examples
c

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

Solution

  • 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.

    You'll also need to flush stdin after each scanf() in case the user enters more than they're supposed to.

    #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