Here is what my professor told me to to.
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:
My problem is using sscanf. I'm not exactly sure how to use it so that it will only return a number if and only if the user enters a number. I'm guessing my if statements are incorrect as well, but I don't know how to use sscanf at all so I don't know how to check if the string only contains floats.
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:
Code:
#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
Comment