Hello all,

I am currently working on a library of functions that I will be able to use in place of scanf(), simply because scanf() is unbelievably stupid. Anyways, I have code written for ints, longs, doubles, chars, but my code for floats is giving me problems. It almost comes out right every time, but it is imprecise in its calculation of the number that the user enters. Please help (especially if you understand the code(and doubly especially if you know the answer)).

Thanks,

monkey_c

Code:

float *getFloat(float **ptr, const char*prompt){
float t1=0, t2=0,placer=0;
char input[1024];
int i=0,flag=0, whereDot=1;
puts("\n\n\n\n\nThis is getFloat\n\n\n\n\n");
//if ptr is not NULL we free the memory and NULL out the pointer
if(*ptr!=NULL){
(void)free(*ptr);
*ptr=NULL;
}
//We allocate one float to be used for storing the users input, pointed to by ptr
if((*ptr=(float*)calloc(sizeof(float),1))==NULL)
return NULL;
//prompt simply states to enter a float
do{
puts(prompt);
//scan in a string, store it in input
fscanf(stdin,"%s",input);
//validate all characters to make sure input is really a float
for(i=0, flag=0;input[i]!='\0';i++){
//find the decimal place
if(input[i]=='.')
whereDot=i;
if(((input[i]<'0')||(input[i]>'9'))&&(input[i]!='.')&&(input[i]!='-')){
flag=1;
break;
}
}
if(flag==1)
fprintf(stderr,"\n!!Each digit in your float must contain a value between 0 and 9!!");
}while (flag==1);
//traverse the array right to left starting at the number before the
//decimal point (the ones column) and multiply the value in each element
//by placer (placer is the value of that column,1's,10's,100's,etc.)
for(placer=1,i=whereDot-1;i>=0;i--,placer*=10)
t1+=(input[i]-48)*placer;
//traverse the array left to right starting at the number after the
//decimal point (the one tenth's column) and multiply the value in each element
//by placer (placer is the value of that column,1/10's,1/100's,1/1000's,etc.)
for(i=whereDot+1,placer=.1;input[i]!='\0';placer*=.1,i++){
t2+=(input[i]-48)*placer;
}
//store the total of the two numbers in the dynamically allocated float
**ptr=(float)((float)t1+(float)t2);
return (float*)*ptr;
}