I have this sample code:
typedef struct {
int num;
char name[100];
float grade;
} Student;
Student newStudent() {
Student a;
printf("New Student\n");
printf("Number: ")
scanf("%d", &a.num);
if(a.num > 0){
printf("Name: ");
scanf("\n%99[^\n]", a.name);
printf("grade: ");
scanf("%f", &a.grade);
}
else {
a.num = -1;
}
return a;
}
The way this code is confusing me for the following reasons:
- I can easily overflow if in the first scanf I input something with spaces, i.e. 239472 8932792.
- How should I interpret the \n%99[^\n] in the second scanf? I've noticed that if I remove the first \n, the whole input system is ruined, even if I do everything right in the first.
- How could I built a better code so that it's overflow proof?