43.9k views
2 votes
Write in C.

Implement the ATOF function

float myAtof(char*string,char*error)

it will convert the input read as a CHAR. array into a floating point number.
1. Your atof function will get two inputs. One for the character array to convert and the other to check for the error. The output of the function will be a floating-point number.

2. If the character array cannot be converted (it includes letters, special characters, etc.) the error will be 1, otherwise 0.

3. If the numbers cannot be converted (error = 1), give an error message to the user.

Sample output:
Enter number:

6

Your num. is 6.0

Enter number: 4.567

Your num is 4.57

Enter number: THIS IS A TEXT

Error occured!

User Bueller
by
7.6k points

1 Answer

3 votes

Final answer:

To implement the custom atof function named myAtof in C, the function prototype is a float return type taking a char array and a char pointer for error checking. It uses the strtof library function to attempt conversion and provides an error message if conversion fails.

Step-by-step explanation:

The student is asking how to implement a custom version of the atof function in the C programming language. The function, named myAtof(), is designed to convert a string (a character array) into a floating-point number. The function takes two arguments: a character array containing the number to be converted and a pointer to a char to check for an error. If the string contains invalid characters that prevent it from being a valid floating-point number, the error character pointer should point to '1', otherwise, it should be '0'. Additionally, the function should provide an error message when a conversion error occurs.

Example Implementation

float myAtof(char *string, char *error) {
char *endptr;
float number;

number = strtof(string, &endptr);

if (string == endptr) {
*error = '1';
printf("Error occurred!\\");
return 0.0f;
} else {
*error = '0';
}
return number;
}

The function uses the standard library function strtof(), which attempts to convert the string to a floating-point number. If the string does not contain a valid number, endptr will point at the beginning of the string, indicating that the conversion failed. The code checks for this condition and assigns '1' to error and '0' otherwise. The converted number or 0.0 is then returned accordingly.

User Asami
by
8.0k points