Question:
Write a program to take data of student as input by the help of
structure student variable.
Do some changes with it.(by using pointers)
And print it.
Problem 1;
I was practicing the structures in C and encounter the problem of (Enter taken by input functions as an input).
after debugging i found that roll and gender is taking enter as an input
So I place a fflush(stdin) between
fgets(std->name, 20, stdin);
and
scanf("%d", &(std->roll));
Later I found that gender is still taking Enter as an input
So I place fflush(stdin) between
scanf("%d", &(std->roll));
and
scanf("%c", &(std->gender));
While taking the input of Second student i found that now name of the second student is taking enter and roll and gender taking garbage vlaue.
So, finally placed fflush(stdin) above
this
fgets(std->name, 20, stdin);
Isn't there any way to resolve this enter issue so that we don't have to think where to place fflush(stdin) by debugging again and again.
Problem 2;
How this buffer input used by the input functions and where actually is this buffer input located (is it in the stack or heap) or in both.
What I have tried:
Header and Global Variables
#include <stdio.h>
struct student
{
char name[20];
int roll;
char gender;
};
void input(struct student *std);
void change(struct student *std);
void display(struct student std);
Main function
int main()
{
struct student Stu1, Stu2;
input(&Stu1);
change(&Stu1);
display(Stu1);
input(&Stu2);
change(&Stu2);
display(Stu2);
return 0;
}
Input Function :
IN THIS FUNCTION I HAVE USED THE FFLUSH(STDIN);
void input(struct student *std)
{
fflush(stdin);
fgets(std->name, 20, stdin);
fflush(stdin);
scanf("%d", &(std->roll));
fflush(stdin);
scanf("%c", &(std->gender));
}
Change function
void change(struct student *std)
{
std->roll += 5;
printf("\n");
}
Display function
void display(struct student std)
{
printf("%s", std.name);
printf("%d\n", std.roll);
printf("%c\n", std.gender);
}