C/C
Expert: Joseph Moore - 2/17/2010
QuestionQUESTION: Dear Sir,
I am finding a problem while i am declareing an array of structure. At the time of scaning the elements, the program treminates and giving the "floating point" related problem. The program using structure is given below:
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[25];
int age;
float salary;
};
void main()
{
struct employee emp[10];
int i=0;
clrscr();
for(i=0;i<2;i++)
{
printf("E n t e r %d\n",i);
scanf("%s %d ",emp[i].name,&emp[i].age);
scanf("%f",emp[i].salary); //error at this point
}
for(i=1;i<2;i++)
{
printf("D i s p l a y %d\n",i);
printf("%s %d %f",emp[i].name,emp[i].age,emp[i].salary);
}
getch();
}
Regards
Kavitha
ANSWER: Hi, Kavitha.
I cannot know for sure what you're seeing without knowing what you're using as input. As a general rule of thumb, though, you need to be very, very careful using scanf and similar functions, especially when reading strings. If you overrun the boundaries of the character array, that will cause problems. Also, because of house scanf works, if you try to enter a first and a last name, it will read each as separate input. Scanf also does not clear the buffer, so you're left with some data inside the buffer after the read (such as the newline character). Chances are, these are the cause of any problems you are seeing.
---------- FOLLOW-UP ----------
QUESTION: Sir,
i have solved my problem by using linkfloat() function.After using this function i can input floating point values into structure array.I want to know the reason for using the linkfloat() function.Please tell me the reason so that i can explain it to other students.
Regards
Kavitha
AnswerPrior to this, I'd never heard of linkfloat. Best I can tell, this is a bad hack to fix what is, in my opinion, a bug in your compiler. I take it you are using Borland TurboC. I've seen a lot of people using TurboC on AllExperts. Borland TurboC is rather old and has several quirks like this.
The problem is (as I understand it), by default, TurboC does not include a floating point implementation when compiling (because, back when TurboC was written/being used, including a floating point implementation in your application could be cost prohibitive). So, you have to actively use floating points in some manner to get it to link in a floating point implementation, and that's what the linkfloat function does. It is a hack function that forces the compiler to include a floating point implementation.