-
Convert string to float
If not use atof, how can I complete the following function which can convert string to float?? Thanks..
Code:
#include <stdio.h>
#include <ctype.h>
#include <math.h>
float strToFloat(const char s[]) {
/* Add your code here */
}
int main() {
printf("%f\n", strToFloat("1"));
printf("%f\n", strToFloat(" 1.23"));
printf("%f\n", strToFloat("-1.23"));
printf("%f\n", strToFloat("1.23456"));
printf("%f\n", strToFloat("0.00000001"));
printf("%f\n", strToFloat("0.0.1"));
printf("%f\n", strToFloat("1E2"));
printf("%f\n", strToFloat("0.0.1"));
printf("%f\n", strToFloat("1.23456E2"));
printf("%f\n", strToFloat("1.23456e3"));
printf("%f\n", strToFloat("2E"));
}
-
Probably the easyest way to do this is to use sscanf().
Code:
float fl;
sscanf(s, "%f", &fl);
return fl;
-
Thank you.
But I can't use sscanf for the question. Is there any other function that I can use?
-
You could just write necessary logic to convert the strings to floats yourself.
If you haven't done anything of this sort before, try your hand at making a basic ASCII to Integer function first. Once you can do this, you should be a lot closer to turning a string into a float.
-
strtod() is part of the standard library, otherwise you'll have to sscanf it yourself
-
Yep, yep - you could look at strtod. I generally use it for floating point input, and strtol for integer input. Have a look at this for an idea of how to implement your code. Of course the linked page deals with strtol, but after reading your documentation for both strtol and strtod, it is fairly trivial to use strtod in place of strtol for your needs.
-
Do this using side-by-side development, i.e. check that your code gives the same answer as sscanf.
Other than that, just approach this one character at a time. Look at the first character, and adjust the value of your float or other member variables accordingly, then move on to the next character. You'll need something to track the sign of the number, and whether you've seen the sign yet, and something to track whether you've seen the decimal point yet, etc.