Reputation: 1
I have written this code to convert a string into float number (IMPLEMENTED MY OWN ATOF() function in c)
the output should be this:
Enter A number:
6
your number is : 6.00
CORRECTED: but I get this.
Enter A number:
6
Press enter to continue:
I am getting this output:
Enter A number:
6
your number is: 0.00
Press enter to continue:
The following is the code that I wrote. I feel like I have missed something with the pointer or might have made mistake in the calculation. But as for as I see, everything seems good for me but why it is giving me 0.00?
#include <stdio.h>
#include <stdlib.h>
#define SIZE 250
float myAtof(char *string, char *error);
int main()
{
char string[SIZE]; // Array declaration.
float fnum1;
char errorState=0;
printf("Enter a number:\n");
gets(string);
fnum1=myAtof(string,&errorState);
if (errorState==0){
printf("Your number is: %.2f \n", fnum1);
}
else if (errorState==1){
printf("Error has been occurred due to inappropriate input!\n");
}
return 0;
}
float myAtof(char* string, char* error){ // Function to convert string into float.
*error != '1';
float num= 0;
float decimalFlag = 1;
int decimalNumberFound = 0;
for(int i = 0; i< strlen(string); i++){
char ch = string[i];
if(ch != '.' && (ch < '0' || ch >'9'))
{
*error ='1';
return 0;
}
if( decimalNumberFound == 1 && ch == '.')
{
*error = '1';
return 0;
}
if(ch = '.')
{
decimalNumberFound = 1;
}
else {
num = num * 10 + (ch - '0');
if(decimalNumberFound ==1)
decimalFlag = decimalFlag * 10;
}
}
num = num / decimalFlag;
return num;
}
Upvotes: 0
Views: 62
Reputation: 57388
I will not tell you where the error is, but remember never to code "this will not happen". Here, you do:
if (errorState==0) {
printf("Your number is: %.2f \n", fnum1);
} else if (errorState==1) {
printf("Error has been occurred due to inappropriate input!\n");
}
You just said, "it will never happen that errorState is neither 0 nor 1".
Try rather:
if (errorState==0) {
printf("Your number is: %.2f \n", fnum1);
} else if (errorState==1) {
printf("Error has been occurred due to inappropriate input!\n");
} else {
printf("Rats! errorCode is %d! This cannot be happening!\n", (int)errorCode);
}
so that whatever happens, you should get some input.
Upvotes: 3