Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect empty string from fgets

Tags:

c

input

fgets

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!

like image 391
KWJ2104 Avatar asked Nov 08 '11 23:11

KWJ2104


1 Answers

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.

like image 146
orlp Avatar answered Oct 31 '22 09:10

orlp