How to check if C string is empty

后端 未结 12 1154
一个人的身影
一个人的身影 2021-01-30 19:41

I\'m writing a very small program in C that needs to check if a certain string is empty. For the sake of this question, I\'ve simplified my code:

#include 

        
12条回答
  •  粉色の甜心
    2021-01-30 20:24

    Typically speaking, you're going to have a hard time getting an empty string here, considering %s ignores white space (spaces, tabs, newlines)... but regardless, scanf() actually returns the number of successful matches...

    From the man page:

    the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

    so if somehow they managed to get by with an empty string (ctrl+z for example) you can just check the return result.

    int count = 0;
    do {
      ...
      count = scanf("%62s", url);  // You should check return values and limit the 
                                   // input length
      ...
    } while (count <= 0)
    

    Note you have to check less than because in the example I gave, you'd get back -1, again detailed in the man page:

    The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

提交回复
热议问题