I am new to the C language.
I want to determine the fgets() length at runtime, something like:
int i;
char str[100];
scanf("%d",&i);
fgets(str, i, stdin);
At execution, the program just skips my fgets() line, there is no error; I don't see anything in dbg.
If I set a concrete value for the input length, it works fine.
fgets(str, 10, stdin);
Could somebody please help me understand what is happening? According to this C Reference the second argument is a simple int.
This is the full example:
#include <stdlib.h>
#include <stdio.h>
int main() {
int i;
char str[100];
puts("Enter a number: ");
scanf("%d", &i);
fgets(str, i, stdin);
printf("String contents: %s", str);
return 0;
}
Vs. hard-coded value which is working fine: #include <stdlib.h> #include <stdio.h>
int main() {
char str[100];
fgets(str, 10, stdin);
printf("String contents: %s", str);
return 0;
}
By calling scanf
, you solicit the user to enter a line of text. scanf("%d", &i);
consumes the numeral the user enters in that line but leaves the new-line character in the buffer. The later fgets
reads that new-line character, and that causes it not to read any further, so you get an empty line from fgets
. Use getchar()
after your call to scanf()
to consume the new-line character:
int i;
char str[100];
scanf("%d",&i);
getchar();
fgets(str, i, stdin);
Or, more thoroughly, after scanf
, consume the entire rest of the line up to the new-line character, in case the user entered other text:
int i;
char str[100];
scanf("%d",&i);
while (getchar() != '\n')
;
fgets(str, i, stdin);