# Buffer and number conversions? (in C)

This topic is 4040 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I have a function that reads a file and places all characters in a buffer, for futher handlings. Now I have a buffer that will be filled when its at a number. So the 'characters' of the number (plus '.' when it goes to decimals) are one by one in the buffer. Now I want to place that number in an double type, and modify it. Than I need to put that number in the output buffer, so it can be written to a certain file. Well...any methodes to do this? Maybe I shouldn't put the number in a buffer first, but just make it the number and multiply with 10 when another numbers comes and add the new number? Or...? Thanks a lot :) Decrius

##### Share on other sites
If I understand things correctly, you have a character buffer (char*) populated with numbers, possibly a decimal point, and more numbers, and you want to turn this into a double type, since it is, ostensibly, a correct representation of a double. Since you're using C, I'll point you to double atof(char*), which converts a char* to a double.

To then convert from a double (that you're modified in some way) to a buffer, I'll point you to int sprintf (char *str, const char *format, ...). This takes arguments just like printf, but sends the output to a buffer, rather than the standard output.

Now, all of this in action:

bool PlayWithDouble(char* pszBuff, double dNumberToAdd){    double dNew = atof(pszBuff);    dNew += dNumberToAdd;    return (sprintf(pszBuff, "%f", dNew) >= 0);}

As usual, this would be much easier and safer in C++, but if certain constraints apply that limit you to C, who am I to judge. [smile]
-jouley

##### Share on other sites
To be parallel with sprintf(), there is also sscanf() (which can also read multiple things; it works just the way that scanf() works on the standard input, except out of the buffer instead).

Of course, that also gives us a hint towards how we can do the reading "directly" without a buffer: via scanf(). However, you may need more care WRT error handling this way.

There is also strtod(), which is a little more "heavy-duty" than atof() but does more or less the same thing.

BTW, jouley's sample brings up an important point about buffering - be very careful if you want to use the same buffer for input and output. In particular, if the new double's text representation has a different length, then you'll either have some garbage in the buffer (leftover from the old representation), or you'll overwrite part of the rest of the string. Unless, of course, you take care to shift the rest of the buffer contents first. Not easy to arrange, though.

##### Share on other sites
Okay, thank you both :)

I got it working now :D, thanks!

Decrius