0

fgets gets skipped when i run my code. the scanf lines work just fine.

Here is the relevant code from a header file:

#ifndef UNTITLED16_FUNCTIONS_H
#define UNTITLED16_FUNCTIONS_H

struct student{

    int studentID;
    char studentName[100];
    int age;
}student_t;

void get_information(){
    printf("Type your student ID: ");
    scanf("%i", &student_t.studentID);

    printf("\nType your name: ");
    fgets(student_t.studentName, 100, stdin);

    printf("\nType your age: ");
    scanf("%i", &student_t.age);
}

void print_information(){

    printf("Student id: %i\n", student_t.studentID);
    printf("Name: %s\n", student_t.studentName);
    printf("Age: %i\n", student_t.age);
}

#endif //UNTITLED16_FUNCTIONS_H

Any ideas?

  • Don't mix `scanf` with `fgets` – Eugene Sh. Dec 02 '21 at 18:01
  • so i should use fgets for the others also? –  Dec 02 '21 at 18:02
  • You can use `fgets()` and apply `sscanf()` to the string. Or other functions such as `strtol()` etc. – Weather Vane Dec 02 '21 at 18:02
  • the general recommendation is to avoid `scanf` when possible. – Eugene Sh. Dec 02 '21 at 18:02
  • @EugeneSh. I don't disagree, but you're fighting a losing battle. There's a neverending stream of new learners out there, and every single one of them is using a textbook or tutorial, or listening to an instructor or a YouTube video, inducing them to use `scanf`. And none of those textbooks, tutorials, instructors, or videos are offering the slightest hints about using `scanf` safely: not mixing it with `fgets` or `getchar`, checking the return value, putting a space before `%c`, not trying to read multiple things on one line, etc., etc., etc... – Steve Summit Dec 02 '21 at 18:09
  • 2
    @SteveSummit Well, saving a single soul still worth it, no? :) – Eugene Sh. Dec 02 '21 at 18:09
  • it cirtanly is for me, thank you for the clarification ;) –  Dec 02 '21 at 18:30

0 Answers0