I was wondering if fgets()
reads a new line char from user input, i.e. the keyboard. Here is some sample code I wrote:
while (1) {
char userInput[3] = {'\0', '\0', '\0'};
fgets(userInput, 3, stdin);
flushStdin();
printf("%s\n", userInput);
}
If I type '2', I am reprompted to enter another char, and the following result is:
$ 2
$ 3
2
$
I understand how fgets()
work, so it may be that my logic is incorrect. The desired output is:
$ 2
2
$
I think fgets() will read up to 1 less than the buffer size given. It will take the \n from the input when you hit enter. You could use something like this to cleanse the input for strings or use scanf() for int input
void readLine(char* buffer, int bufferLength, FILE* file)
{
fgets(buffer, bufferLength, file);
int len = strlen(buffer);
if(len > 0 && buffer[len - 1] == '\n'){
buffer[len - 1] = '\0';
}
}