Creating a fixed length output string with sprintf containing floats

Posted by Kungi on Stack Overflow See other posts from Stack Overflow or by Kungi
Published on 2010-05-27T09:37:56Z Indexed on 2010/05/27 9:41 UTC
Read the original article Hit count: 372

Hi,

I'm trying to create a file which has the following structure:
- Each line has 32 bytes - Each line looks like this format string: "%10i %3.7f %3.7f\n"

My Problem is the following: When i have a negative floating point numbers the line gets longer by one or even two characters because the - sign does not count to the "%3.7f".

Is there any way to do this more nicely than this?

if( node->lng > 0 && node->lat > 0 ) { 
    sprintf( osm_node_repr, "%10i %3.7f %3.7f\n", node->id, node->lng, node->lat );
} else if (node->lng > 0 && node->lat < 0) {
    sprintf( osm_node_repr, "%10i %3.7f %3.6f\n", node->id, node->lng, node->lat );
} else if (node->lng < 0 && node->lat > 0) {
    sprintf( osm_node_repr, "%10i %3.6f %3.7f\n", node->id, node->lng, node->lat );
} else if ( node->lng < 0 && node->lat < 0 ) { 
    sprintf( osm_node_repr, "%10i %3.6f %3.6f\n", node->id, node->lng, node->lat );
}

Thanks for your Answers,
Andreas

© Stack Overflow or respective owner

Related posts about c++

Related posts about sprintf