-
'gets function error'
my program doesn't return any errors but if u compile it (please do)
u will see that something is wrong. i think is because of the 'gets' function i used but i can't use the 'scanf' function because it only reads the first word please help me resolve this problem.It would be deeply appreciated.
Code:
#include<stdio.h>
#include<conio.h>
struct product
{
char name[30];
int stock;
float price, discount;
};
void main()
{
struct product p[3];
int i;
float temp;
// clrscr();
for(i=0;i<3;i++)
{
printf("Enter product name :");
gets(p[i].name);
printf("\nEnter Stock :");
scanf("%d",&p[i].stock);
printf("\nEnter Price :");
scanf("%f",&temp);
p[i].price = temp;
printf("\nEnter Discount :");
scanf("%f",&temp);
p[i].discount = temp;
printf("\n\n");
// fflush(stdin);
}
// clrscr();
for(i=0;i<3;i++)
{
printf("Name=%s, Stock=%d, Price=$%.2f, Discount=%.2f%.\n", p[i].name, p[i].stock, p[i].price,p[i].discount);
}
getch();
}
-
Use int main, not void main
Use fgets(), not gets()
See the FAQ's
-
You need an extra fgets at the bottom of the loop (or something else to consume the newline).
-
Code:
scanf("%[^\n]"); // Will read everything up until the newline character.
That is just an example, it is still recommended that you only use scanf() for getting number inputs.
As mentioned fgets() is better than gets() as you can specify the amount of chars you want to accept (protects you from buffer overflows).
Your problem is that the product name variable is being consumed with the newline character. You need to find a way to flush the input buffer.
FAQ > Flush the input buffer - Cprogramming.com