How to check if C string is empty

Since C-style strings are always terminated with the null character (\0), you can check whether the string is empty by writing

do {
   ...
} while (url[0] != '\0');

Alternatively, you could use the strcmp function, which is overkill but might be easier to read:

do {
   ...
} while (strcmp(url, ""));

Note that strcmp returns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is nonempty.

Hope this helps!


If the first character happens to be '\0', then you have an empty string.

This is what you should do:

do {
    /* 
    *   Resetting first character before getting input.
    */
    url[0] = '\0';

    // code
} while (url[0] != '\0');

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.


If you want to check if a string is empty:

if (str[0] == '\0')
{
    // your code here
}

Tags:

C

String