tags:

views:

410

answers:

3

I'm trying to split real numbers in a C program using the decimal point as the delimter such that such that say, 1234.56 yields

(int) whole_num = 1234 (int) fraction = 56

Any ideas how I can go about doing this? Its been a loooong while since I mucked around with C, see? :)

+4  A: 
void split( double num, int& whole_number, double& fraction) {
    fraction = modf(num, &whole_number);
}

This works since modf takes the integer part of the double and returns the fractional part.

Nathaniel Flath
-1 Use modf if you're actually decomposing a floating-point number.
Chris Jester-Young
Wow, thanks Daniel! That was quick- and certainly cleaner than some of the other solutions I pulled up online using strtok(). I'm curious to see what others come up with.
freakwincy
Chris, fixed that problem.
Nathaniel Flath
qrdl
+3  A: 

Assuming you want to split a string.

strtok_r and your favorite string-to-num function like strtol

laalto
+1 for mention of strtok_r. :-)
Chris Jester-Young
+1  A: 

If you're dealing with an actual floating-point number, as opposed to a string representation of such, you should use modf for splitting out the integral and fractional parts.

Perl's split splits by regex, so to replicate full functionality you'd need a regex library. For general string-splitting, you may be able to use strtok, but because it changes the string in-place, strtok_r (described on the same page) is recommended instead.

Chris Jester-Young