I have a char array buffer that I am using to store characters that the user will input one by one. My code below works but has a few glitches that I can\'t figure out:
It's odd that no-one has mentioned this possibility:
char Buffer[8]; //holds the byte stream
int i = 0;
while (i < sizeof(Buffer) && (charInput = get_the_users_character()) != EOF)
{
Buffer[i] = charInput;
i++;
// Display a response to input
printf("Buffer is %.*s!\n", i, Buffer);
}
This notation in the printf() format string specifies the maximum length of the string to be displayed, and does not require null termination (though null termination is ultimately the best way to go -- at least once you leave this loop).
The while
loop is more plausible than a simple if
, and this version ensures that you do not overflow the end of the buffer (but does not ensure you leave enough space for a trailing NUL '\0'
. If you want to handle that, use sizeof(Buffer) - 1
and then add the NUL after the loop.