Search code examples
cstructgetchar

What is the exact work, that the getchar() is doing?


Here, if I don't use getchar() the output is misbehaving:

Check here to see the output console

What exactly is the getchar() doing here ?

And what is it holding until another input gets invoked ?

And how will the next input be invoked here in this case ?

My code:

//To take 3 students data using stucture which is user defined.
#include<stdio.h>
#include<stdlib.h>
//#include<conio.h>
struct student
{
    char reg_number[200];
    char name[200];
    int marks_obt;
};
int main()
{
    struct student stud1,stud2,stud3;
    printf("Enter registration number of student 1 : ");
    gets(stud1.reg_number);
    printf("Enter name of student 1 : ");
    gets(stud1.name);
    printf("Enter marks of student 1 : ");
    scanf("%d",&stud1.marks_obt);
    system("cls");
        //getchar();
    printf("Enter registration number of student 2 : ");
    gets(stud2.reg_number);
    printf("Enter name of student 2 : ");
    gets(stud2.name);
    printf("Enter marks of student 2 : ");
    scanf("%d",&stud2.marks_obt);
    system("cls");
        //getchar();
    printf("Enter registration number of student 3 : ");
    gets(stud3.reg_number);
    printf("Enter name of student 3 : ");
    gets(stud3.name);
    printf("Enter marks of student 3 : ");
    scanf("%d",&stud3.marks_obt);
    system("cls");
    
    printf("ID of student 1 is %s \n Name of student 1 is %s \n Marks obtained by stdent 1 is %d",stud1.reg_number,stud1.name,stud1.marks_obt);
    printf("\n\n");
    printf("ID of student 2 is %s \n Name of student 2 is %s \n Marks obtained by stdent 2 is %d",stud2.reg_number,stud2.name,stud2.marks_obt);
    printf("\n\n");
    printf("ID of student 3 is %s \n Name of student 3 is %s \n Marks obtained by stdent 3 is %d",stud3.reg_number,stud3.name,stud3.marks_obt);
    //getch();
} 

Solution

  • There are already comments and a correct answer that should be enough, but judging by your last comment it seems that you didn't yet understand what's going on.

    This line:

    scanf("%d",&stud1.marks_obt);
    

    Parses an integer, for that you press Enter, when you do that a \n is added to the stdin buffer, and remains there, it is not parsed by scanf.

    After that:

    gets(stud2.reg_number);
    

    Will parse that \n character and store it in stud2.reg_number, and the program moves on.

    When you use getchar(), it parses the \n and leaves the stdin buffer empty again so the gets has nothing to parse and waits for your input, correcting the problem, it's still a flimsy solution, but it works in this particular case.

    Moral of the story, don't mix scanf with gets, fgets at least, since, as stated, gets was removed from the standard in C11. The reason why some compilers still support it is beyond me.