Search code examples
cbufferfgets

Minimum buffer length to read a float


I'm writing a small command-line program that reads two floats, an int, and a small string (4 chars max) from stdin. I'm trying to figure out the buffer size I should create and pass to fgets. I figured I could calculate this based on how many digits should be included in the maximum values of float and int respectively, like so:

#include <float.h>
#include <limits.h>

...

int fmax = log10(FLOAT_MAX) + 2;     // Digits plus - and .
int imax = log10(INT_MAX) + 1;       // Digits plus -
int buflen = 4 + 2*fmax + imax + 4;  // 4 chars, 2 floats, 1 int, 3 spaces and \n

...

fgets(inbuf, buflen + 1, stdin);

But it's occurred to me that this might not actually be correct. imax ends up being 10 on my system, which seems a bit low, while fmax if 40. (Which I'm thinking is a bit high, given that longer values may be represented with e notation.)

So my question is: is this the best way to work this out? Is this even necessary? It just feels more elegant than assigning a buffer of 256 and assuming it'll be enough. Call it a matter of pride ;P.


Solution

  • This type of thing is a place where I would actually use fscanf rather than reading into a fixed-size buffer first. If you need to make sure you don't skip a newline or other meaningful whitespace, you can use fgetc to process character-by-character until you get the the beginning of the number, then ungetc before calling fscanf.

    If you want to be lazy though, just pick a big number like 1000...