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!
I think this is the most readable (but not performant):
if (strlen(input) != 0) {
printf("hi");
}
But for the sake of teaching here is your style, but then fixed:
if (input[0] != '\0') {
printf("hi");
}
Why input[0]
? Because input
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.