Reputation: 57
I have written below program which tries to read and print the values of a structure. I thought that scanf ignores the /n for all kinf of data except for char but when i run the below program and provide the first input as an integer. I dont get the o/p for name variable. Why??
#include <stdio.h>
#include <string.h>
struct employee
{
int empno;
char name[10];
float p_money;
};
int main()
{
struct employee e;
struct employee *ptr;
ptr = &e;
printf("please enter the empno \n");
scanf("%d", &(ptr->empno));
printf("please enter the name \n");
gets(ptr->name);
//scanf("%d", &(ptr->empno));
printf("please enter the money \n");
scanf("%f", &(ptr->p_money));
printf("Roll No: %d\n", ptr->empno);
printf("Name: %s\n", ptr->name);
printf("Money: %f\n", ptr->p_money);
getchar();
return 0;
}
Execution:
please enter the empno
10
please enter the name
please enter the money
100.99
Roll No: 10 Name: Money: 100.989998
please enter the empno
10jackal
please enter the name
please enter the money
100.99
Roll No: 10 Name: jackal Money: 100.989998
Upvotes: 2
Views: 2286
Reputation:
1use fgets
instead of gets
... gets
is bad.
The reason why gets
is bad:
gets
Reads characters from the standard input until enter
(new line is encountered.) is pressed.
In your case, name[10]
, and you are doing gets(name)
. gets
does not know how big the name
is... If you enter 9 character, it is okay.
But what if you enter more than 9 char? gets()
continues to write all the char
past the memory which doesn't belong to you hence causing "Undefined Behavior
"
Upvotes: 0