0

gets(edu.classes[i].students[j].name);

I would like to know why the compiler skips this line after debugging and does not input into name? Is it legal to invoke gets function on that way?

Note: Once I use scanf("%s" , ... ) - it works!

scanf("%s",edu.classes[i].students[j].name);

(I know that I did not free the memory allocations and checked if the allocations were not failed - I know that it is necessary! It's only time issue) :)

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

#define SIZE 20

typedef struct
{
char name[SIZE];
int id;
}Student;

typedef struct
{
Student *students;
int num_students;
char teacher[SIZE];
}Class;

typedef struct
{
Class *classes;
int num_classes;
}Education;

int main()
{
int i, j;
Education edu;
puts("how many classes?");
scanf("%d", &(edu.num_classes));
edu.classes = (Class*)malloc((edu.num_classes) * sizeof(Class));
if (edu.classes == NULL)
{
    printf("ERROR allocation\n");
    exit(1);
}
for (i = 0; i < edu.num_classes; i++)
{
    puts("enter num of students");
    scanf("%d", &(edu.classes[i].num_students));
    edu.classes[i].students = (Student*)malloc((edu.classes[i].num_students) 
* sizeof(Student));
    for (j = 0; j < edu.classes[i].num_students; j++)
    {
        puts("enter student's name");
        gets(edu.classes[i].students[j].name); // this is the problematic line
        puts("enter id");
        scanf("%d", &(edu.classes[i].students[j].id));
    }
}
return 0;
}

1 Answers1

0

I think it is seeing the newline character that was produced due to hitting the enter key. gets then stops reading. Try eating those special characters before gets sees them. Or use scanf with %s which eats any leading whitespace as you have seen it works.

E. van Putten
  • 615
  • 7
  • 17