How to detect empty string from fgets

2019-07-03 14:54发布

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!

标签: c input fgets
4条回答
等我变得足够好
2楼-- · 2019-07-03 15:09

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).

查看更多
forever°为你锁心
3楼-- · 2019-07-03 15:13

The obvious way would be something like:

if (input[0] != '\0')
   printf("hi");

Although using strlen will work, it's potentially quite wasteful -- it turns an O(1) operation into O(N).

查看更多
爷的心禁止访问
4楼-- · 2019-07-03 15:30

To be on the safe side, better use this:

if(u_input[0] == '\n' && u_input[1] == '\0'){
    printf("hi");
}
查看更多
Bombasti
5楼-- · 2019-07-03 15:36

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.

查看更多
登录 后发表回答