C/c question
Expert: Zlatko - 12/2/2011
Questionam gettin error when i try to read float type data in array of structures.. the program terminates after reading name....... can u help me please...........
after trying following code also am getting same problem......
#include <stdio.h>
#include <conio.h>
struct test
{
int x;
char name[100];
float marks;
};
int main(void)
{
int i;
struct test p[2];
for(i = 0; i < 2; i++)
{
clrscr();
printf("Enter The Roll No. : ");
scanf("%d", &p[i].x);
fflush(stdin);
printf("Enter The Name : ");
scanf("%s", p[i].name);
fflush(stdin);
printf("Enter The percentage marks: ");
scanf("%f", &p[i].marks);
}
printf("\n");
for(i = 0; i < 2; i++)
{
printf("Roll No of \"%s\" is %d, getting %5.3f marks.\n", p[i].name, p[i].x, p[i].marks);
}
getch();
return 0;
}
AnswerHello Anu.
When I tested your program. It worked well as long as I gave it correct input. If it was asking for a number and I gave it invalid characters, then it would have problems. The problem with scanf is that it takes what it can use from the input, and leaves the rest. What is left over can cause problems on the next call to scanf. For example, if you want to scanf a number and the user inputs 123abc, the scanf will take 123, and leave abc. The next call to scanf will try to use abc.
I describe my idea of the correct way to do C input at this link:
http://sites.google.com/site/zlatkoscodingtopics/console-input-with-c
I include a sample program there. You can use the sample program as a starting point for your work.
In your program, you should avoid doing fflush(stdin). That may work on some compilers, but it is not standard C. If you don't believe me, you can read more about it at this link:
http://www.gidnetwork.com/b-57.html
Best regards
Zlatko