I need to use arithmetic on monetary values ($20.32, etc.) while using fscanf, but I don't know how to parse $ and the float value separately. Any help please?!?!?!?!
I need to use arithmetic on monetary values ($20.32, etc.) while using fscanf, but I don't know how to parse $ and the float value separately. Any help please?!?!?!?!
Well, if you KNOW that the dollar sign is always going to be there, you could always read it in as a string, copy everything after the $ into a different string, and then use the atof() function to turn that into a floating point number. But you might want to write a few lines to check and make sure that the $ is actually present.
starX
www.axisoftime.com
i just looked up the atof function, and the example showed that the string had to be in quotes. is it possible to atof the monetary values depsite the number not being in qutes? Thanks
The following example uses sscanf, a close relative of fscanf, with a format specifier "$%lf".Originally posted by rtransfi
I need to use arithmetic on monetary values ($20.32, etc.) while using fscanf, but I don't know how to parse $ and the float value separately. Any help please?!?!?!?!My output is as follows.Code:#include<stdio.h> int main(void) { int i; const char *text[4] = { "$20.32", "$15.99", "not a number", "15.49" }; double value[4], sum = 0.0; for ( i = 0; i < 4; ++i ) { printf("text[%d] = \"%s\"", i, text[i]); if ( sscanf(text[i], "$%lf", &value[i]) == 1 ) { printf("; value[%d] = %.2lf", i, value[i]); sum += value[i]; } else { fputs(" -- failed to scan", stdout); } putchar('\n'); } printf("sum = %.2lf (or write as $%.2lf)\n", sum, sum); return 0; }HTHCode:text[0] = "$20.32"; value[0] = 20.32 text[1] = "$15.99"; value[1] = 15.99 text[2] = "not a number" -- failed to scan text[3] = "15.49" -- failed to scan sum = 36.31 (or write as $36.31)
Unless I'm completely off my rocker (very possible, as I haven't slept in days), you only need quotes for string literals. If you have a pointer to string you won't need the quotes.
starX
www.axisoftime.com
Which bit are you refering to?Originally posted by starX
Unless I'm completely off my rocker (very possible, as I haven't slept in days), you only need quotes for string literals. If you have a pointer to string you won't need the quotes.
starX
www.axisoftime.com
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
I believe it was in reply to:Originally posted by Hammer
Which bit are you refering to?
Originally posted by rtransfi
i just looked up the atof function, and the example showed that the string had to be in quotes. is it possible to atof the monetary values depsite the number not being in qutes? Thanks
Quzah.
Hope is the first step on the road to disappointment.