Guy Guy - 4 years ago 96
C Question

Using fgets() to put a character into an array creates automatic input?

I want to take in a single character of input that the user types in, and then print it back out using the printf() and fgets() methods (this is all a part of a bigger program, but this is the isolated problem).

include <stdio.h>
include <stdlib.h>
char input[1];

int main(){
printf("Please enter the minimum value the random number can be: ");
fgets(input, sizeof(input), stdin);
printf("\n%c", input[0]);
}


How I expect the above code to work



I would think that it would print out the printf() message, and then wait for input from the user. No matter what they typed in, I would then expect it to take the first character of that input and print it back out again one line down.

How the above code actually works



The program prints the initial printf() statement, then prints out a blank line underneath, and then the program terminates.

Why in the world is this?? Why is the code responding in that way and not how I expect?

Answer Source

From C11, chapter 7.21.7.2, fgets() synopsis and description, (emphasis mine)

char *fgets(char * restrict s, int n, FILE * restrict stream);

The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. [...]

and regarding the reason behind one less,

[...] A null character is written immediately after the last character read into the array.

In your case, the value of n supplied is 1, hence fgets() actually does not read anything!!

Solution: You need to change your array size two 2, one element for the input and one element for the terminating null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download