0

This is the program. Which basically takes input and displays output (I'm still learning). The problem is, the output isn't correct and is giving garbage values for the '1' index number.

Here's the code:

typedef struct {
    char name[256];
    int id;
    int classes;
} students;

int main(void) {
    students a[3];
    for (int i = 0; i < 3; i++) {
        //fgets(word, sizeof(word), stdin);
        fgets(a[i].name, 100, stdin);
        scanf("%d", &a[i].id);
        scanf("%d", &a[i].classes);
    }
    for (int i = 0; i < 3; i++) {
        printf("Your name is: %s", a[i].name);
    //  printf("\n");
        printf("Your id is: %d", a[i].id + 1);
        printf("\n");
        printf("Your class is: %d", a[i].classes + 1);
        printf("\n");
        printf("\n");
    }
}

Random input that I provide is:

as
2
33
asd
3
44
asdasd
4
55

However, the output is (unexpected):

Your name is: as
Your id is: 3
Your class is: 34

Your name is: 
Your id is: -163754449
Your class is: 129100402

Your name is: asd
Your id is: 4
Your class is: 45

Please let me know why is this happening.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Anoneemus
  • 149
  • 10

0 Answers0