Search code examples
cinputbufferclion

How to find number of chars in input buffer before emptying the buffer?


The code I'm trying to create need to convert input numbers from 2-9 base to decimal. (c language)

The plan is to check each input char by itself to see if it viable with the given base, and if yes then calculate its decimal value via: char * base^(digit index -1) (wasn't sure how to write this but most people here probably know what I mean)

However there is no guarantee on how many numbers the user will input and since getchar() will give the first char that was input that mean the "power" will start from the highest value.

The problem is- how to find out how many chars are in the buffer without destroying the buffer? I can find out how many chars are in the buffer but afaik it would require me to pull them all out.

I still haven't tried anything as I don't how to approach the problem.


Solution

  • The C standard does not provide a way to know how many characters are in the input buffer without reading them.1 C implementations might provide such a feature as an extension. However, it is not necessary to process digits and convert to another base. Simply keep a running value that starts at zero. When each digit is read, multiply the running value by the base and add the new digit. For example, when reading “345” as octal, start with 0, see the “3”, calcluate 0•8+3 = 3, see the “4”, calculate 3•8+4 = 28, see the “5”, calculate 28•8+5 = 229.

    In other situations where you do need the length of a string before processing earlier parts of it, read the entire string, using malloc and realloc to allocate enough memory to hold the string. Once the entire string is read, its length is known, and it can be processed in any order desired.

    Footnote

    1 There are file-positioning functions that can be used to scan through a file and then back up to earlier parts, but these will not work on an input stream from an interactive device.