0

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:

  1. I can easily overflow if in the first scanf I input something with spaces, i.e. 239472 8932792.
  2. 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.
  3. How could I built a better code so that it's overflow proof?
Daniel Oscar
  • 287
  • 1
  • 9
  • 1
    Your code is already overflow proof... – Aplet123 Nov 16 '20 at 14:59
  • @Aplet123, it isn't... If for number I enter something like "3 3", then the console will show "Name: grade:". Any input thereafter is badly formatted. – Daniel Oscar Nov 16 '20 at 15:02
  • First two answers there describe problems associated with `scanf()` function and how to mitigate them in great detail: https://stackoverflow.com/questions/2430303/disadvantages-of-scanf – anfauglit Nov 16 '20 at 15:02
  • That's not an overflow, that's just input being buffered. – Aplet123 Nov 16 '20 at 15:03
  • _"...How could I built a better code so that it's overflow proof"_ This question is answered all over this site. Which of these have you already looked at? – ryyker Nov 16 '20 at 15:08

0 Answers0