2

A string is input as a fraction, how can I convert this string to float?

In the below code it always show the first number only without any calculations i.e : 2.00

int main (void)
{
    string fraction = "2/4";
    float sum = atof(fraction);
    printf("sum : %.2f\n",sum);
    return 0;
}
Hannu
  • 11,685
  • 4
  • 35
  • 51
Hussein
  • 99
  • 1
  • 9
  • 1
    You need to split the string into a nominator and denominator string and then apply `atof` to each individually. – doubleYou Jan 05 '18 at 12:50
  • 2
    How is this code even compiling in C? There is no `string` data type in C. Also, `atof` expects `const char*` as input.. – sgarizvi Jan 05 '18 at 12:50
  • This duplicate has all the tools you'll need to do this. It's by no means a beginner's topic though. K & R has a good chapter on expression parsing. – Bathsheba Jan 05 '18 at 12:53

2 Answers2

3

First of all, your assumption is wrong.

A string like "2/4", is "2/4", it's not "0.5", i.e., it does not evaluate itself to produce the result of the expected expression.

That said, atof() family is not safe (at least, poor with reporting / handling error conditions, which, in your particular case, would have been very useful, should you have checked the return code), please use strtod() and family.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

You cannot do this directly. With atof you e.g. change "2.034" to 2.034 (f), but not an expression (with a division in your case).

Instead, if you know there will be always a divider symbol, search for the divider symbol, than extract the left and right part, use atoi (string to integer), and divide the two integers (after casting to float).

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
  • the string will always be in the format "1/4" , i was able to extract the left and right part but am not able to convert them to integer , always gives me error message . – Hussein Jan 05 '18 at 21:02
  • What error message? – Michel Keijzers Jan 05 '18 at 21:05
  • int main () { char str[] ="1/4"; char * pch; pch = strtok (str,"/"); int intpch[2]; while (pch != NULL) { for (int i = 0 ; i < 2 ; i++) { intpch[i] = atoi(pch); pch = strtok (NULL, "/"); } } float result = intpch[0]/intpch[1]; printf("Result %i / %i is : %.2f\n ",intpch[0],intpch[1],result); return 0; } // the result is 0.00 – Hussein Jan 06 '18 at 10:03
  • it has worked finally – Hussein Jan 06 '18 at 10:21
  • int main () { char str[] ="1/4"; char * pch; pch = strtok (str,"/"); float floatpch[2]; while (pch != NULL) { for (int i = 0 ; i < 2 ; i++) { floatpch[i] = atof(pch); pch = strtok (NULL, "/"); } } float result = floatpch[0]/floatpch[1]; printf("Result %.2f / %.2f is : %.2f\n ",floatpch[0],floatpch[1],result); return 0; } – Hussein Jan 06 '18 at 10:21