Search code examples
cstructscanffgets

Issues with scanf()


I have a program I'm using (quiet simple) that requires an input from the user using scanf. These values are stored into a struct array. Anyways, I think I have all of the syntax down correctly (if I don't please correct me), but whenever I want to printf to see the results, I don't get a value from ID[i].Middle_Name. It seems as though it's empty, for reasons I don't understand. I tried to add a print statement to try and debug it but still nothing. Maybe I'm missing something?

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdarg.h>

struct Students{
  char First_Name[20];
  char Last_Name[20];
  char Middle_Name[20];
  int Age;
};

int main(void){
    int n = 0;  //number of students
    int i = 0;      //counter

  printf("Please enter the total number of students in your class: ");
  scanf("%d", &n);
  struct Students ID[n];
  printf("\n");

  printf("******************** \n");
  printf("After entering student info, they are displayed in full_name/middle_name/age order. \n");
  printf("******************** \n");

  for(i = 1; i <= n; i++){
      printf("Please enter the first name of student with  ID: %d \t", i);
      scanf("%s", (ID[i].First_Name));
      printf("\n");

      printf("Please enter the last name of student with ID: %d \t", i);
      scanf("%s", (ID[i].Last_Name));
      printf("\n");

      printf("Please enter the middle name of student ID: %d \t", i);
      scanf("%s", (ID[i].Middle_Name)); 
      printf("\n");

      printf("Please enter the age of student ID: %d \t", i);
      scanf("%d", &(ID[i].Age));
      printf("\n");

  }
  printf("In your class, we have: \n");
  printf("%s", ID[1].Middle_Name);

  for(i = 1; i <= n; i++){
      printf("%s \t", ID[i].First_Name); 
      printf("%s \t", ID[i].Last_Name); 
      printf("%s \t", ID[i].Middle_Name); 
      printf("%d \n", ID[i].Age); 
  }
  return(0);
}

Solution

  • You have to start with i = 0 instead of i = 1 to get the first element of your array. And you should replace the i <= n by i < n.

    for(i = 0; i < n; i++)
    {
        ...
    }