Write a function that converts a string to a float and returns a float.
Test your function by entering f4 and with 4f. Both should say
Data entered was not a number. Try again.
and ask the user to type in another number.
Here's what I have so far.
Code:
Expand|Select|Wrap|Line Numbers
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #define MAX_SIZE 80
- void readString(char prompt[], char str[]);// Exercise 1
- float readNumber(char prompt[], char str[]);// Exercise 2
- int main()
- {
- char str[MAX_SIZE];
- printf("You entered: %f\n", readNumber("Please enter a number: ", str));
- }
- void readString(char prompt[], char str[]) //This asks the user for a string
- {
- printf("%s", prompt);
- gets(str);
- }//Exercise 1
- float readNumber(char prompt[], char str[]) //This function will convert the string in to a float using readString
- {
- int flag = 0; //0 means no; 1 means yes
- int i;
- float number;
- readString(prompt, str);
- sscanf(str, "%f", &number);
- if(number == 0)
- {
- while(flag == 0)
- {
- printf("Data entered was not a number, Try again.\n");
- readString(prompt, str);
- sscanf(str, "%f", &number);
- if(number != 0)
- flag = 1;
- }
- }
- return number;
- }//Exercise 2