I'm trying to detect the input of fgets from stdin as empty (when I press enter without entering in anything). Here is my program:
int main()
{
char input[1000];
printf("Enter :");
fgets(input, 1000, stdin);
input[strlen(input) - 1] = '\0';
if(input != '\0'){
printf("hi");
}
return 0;
}
I want to do some sort of condition which makes it not print anything, but clearly this way isn't right. I also tried NULL, which did not work.
Thanks!
fgets will return a '\n' when the return key is pressed; this makes the total string "\n\0". You can do a string comparison with this value, but a more robust solution is to 'strip' or 'trim' the string to remove all leading and trailing whitespace (which you should do anyway before any processing) and then check for an empty string.
The easiest modification is to check whether
(*input!='\n')
. I should note that this also requires you to remove the null-terminating code, which strips out this newline (by design, presumably).The obvious way would be something like:
Although using
strlen
will work, it's potentially quite wasteful -- it turns an O(1) operation into O(N).To be on the safe side, better use this:
I think this is the most readable (but not performant):
But for the sake of teaching here is your style, but then fixed:
Why
input[0]
? Becauseinput
acts like a pointer to the first element of the array if you compare it like that and you first have to dereference it to make the comparison useful.