76

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 <stdio.h>
#include <string>

int main() {
  char url[63] = {'\0'};
  do {
    printf("Enter a URL: ");
    scanf("%s", url);
    printf("%s", url);
  } while (/*what should I put in here?*/);

  return(0);
}

I want the program to stop looping if the user just presses enter without entering anything.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
codedude
  • 6,244
  • 14
  • 63
  • 99

13 Answers13

90

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 2
    while (url[0] != '\0'); will continue looping so long as the string is NOT empty. You want: while (url[0] == '\0'); – andrewhl Jan 21 '14 at 17:40
  • 5
    Or `!*url` to be awesome. – bambams Sep 17 '14 at 19:03
  • 7
    What about `strlen(url) == 0 ?` ? – Accountant م Apr 14 '19 at 05:18
  • 1
    I believe `strlen(url) == 0` is, sans optimizations, less efficient since `strlen` has complexity linear in the length of the string (it has to iterate until it sees a null character). The other approaches have constant complexity because they only read one character. Maybe the compiler will optimize `strlen(url) == 0` though. – Sam Marinelli Jul 20 '21 at 05:31
27

If you want to check if a string is empty:

if (str[0] == '\0')
{
    // your code here
}
nabroyan
  • 3,225
  • 6
  • 37
  • 56
8

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');
user123
  • 8,970
  • 2
  • 31
  • 52
  • This still doesn't work if the user enters nothing. The cursor just jumps down to the next line instead of submitting nothing. – codedude Mar 18 '13 at 22:01
  • Not really. When the user just clicks enter instead of entering data, the loop should stop running. Right now, all it does it jump down to the next line. – codedude Mar 18 '13 at 22:12
  • Maybe there's a way to check if the user just hits enter? – codedude Mar 18 '13 at 22:13
  • Try using `getchar()`. Apparently, `getchar()` allows you to detect when any key is pressed, but you'd have to print the returned char (technically, int) manually, so it would get quite messy. – user123 Mar 18 '13 at 22:22
  • Oh, that's cool. I think resetting the first char each time may solve that (Like I did after the edit here). This way, if no input is given, it will remain equal to `'\0'` and the loop must then quit. – user123 Mar 18 '13 at 22:25
  • I thought it would too, but apparently not. – codedude Mar 18 '13 at 22:30
  • I'll throw out a guess and assert that `scanf` is writing `'\n'` to your buffer. Try comparing `url[0]` against not only `'\0'`, but `'\n'` as well. If that works, then I guess this is solved. – user123 Mar 18 '13 at 22:32
  • Ooops. That produces an infinite loop. – codedude Mar 18 '13 at 22:37
  • both when I enter nothing and when I enter some text – codedude Mar 18 '13 at 22:38
  • " you'd have to print the returned char (technically, int) manually" -- uh, no ... only if you have echo turned off on your terminal. `scanf` just calls `getchar` repeatedly. – Jim Balter Mar 26 '13 at 04:21
4

You can check the return value from scanf. This code will just sit there until it receives a string.

int a;

do {
  // other code
  a = scanf("%s", url);

} while (a <= 0);
squiguy
  • 32,370
  • 6
  • 56
  • 63
4

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.

Mike
  • 47,263
  • 29
  • 113
  • 177
3

You can try like this:-

if (string[0] == '\0') {
}

In your case it can be like:-

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

;

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • This still doesn't work if the user enters nothing. The cursor just jumps down to the next line instead of submitting nothing. – codedude Mar 18 '13 at 22:00
3

strlen(url)

Returns the length of the string. It counts all characters until a null-byte is found. In your case, check it against 0.

Or just check it manually with:

*url == '\0'
flyingOwl
  • 244
  • 1
  • 5
  • This still doesn't work if the user enters nothing. The cursor just jumps down to the next line instead of submitting nothing. – codedude Mar 18 '13 at 22:01
3

First replace the scanf() with fgets() ...

do {
    if (!fgets(url, sizeof url, stdin)) /* error */;
    /* ... */
} while (*url != '\n');
pmg
  • 106,608
  • 13
  • 126
  • 198
3

The shortest way to do that would be:

do {
    // Something
} while (*url);

Basically, *url will return the char at the first position in the array; since C strings are null-terminated, if the string is empty, its first position will be the character '\0', whose ASCII value is 0; since C logical statements treat every zero value as false, this loop will keep going while the first position of the string is non-null, that is, while the string is not empty.

Recommended readings if you want to understand this better:

Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80
2

I've written down this macro

#define IS_EMPTY_STR(X) ( (1 / (sizeof(X[0]) == 1))/*type check*/ && !(X[0])/*content check*/)

so it would be

while (! IS_EMPTY_STR(url));

The benefit in this macro it that it's type-safe. You'll get a compilation error if put in something other than a pointer to char.

0

It is very simple. check for string empty condition in while condition.

  1. You can use strlen function to check for the string length.

    #include<stdio.h>
    #include <string.h>   
    
    int main()
    {
        char url[63] = {'\0'};
        do
        {
            printf("Enter a URL: ");
            scanf("%s", url);
            printf("%s", url);
        } while (strlen(url)<=0);
        return(0);
    }
    
  2. check first character is '\0'

    #include <stdio.h>    
    #include <string.h>
    
    int main()
    {        
        char url[63] = {'\0'};
    
        do
        {
            printf("Enter a URL: ");
            scanf("%s", url);
            printf("%s", url);
        } while (url[0]=='\0');
    
        return(0);
    }
    

For your reference:

C arrays:
https://www.javatpoint.com/c-array
https://scholarsoul.com/arrays-in-c/

C strings:
https://www.programiz.com/c-programming/c-strings
https://scholarsoul.com/string-in-c/
https://en.wikipedia.org/wiki/C_string_handling

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Pranu Pranav
  • 353
  • 3
  • 8
0

Verified & Summary:

  • check C string is Empty
    • url[0] == '\0'
    • strlen(url) == 0
    • strcmp(url, "") == 0
  • check C string Not Empty
    • url[0] != '\0'
    • strlen(url) > 0
    • strcmp(url, "") != 0
crifan
  • 12,947
  • 1
  • 71
  • 56
-1

With strtok(), it can be done in just one line: "if (strtok(s," \t")==NULL)". For example:

#include <stdio.h>
#include <string.h>

int is_whitespace(char *s) {
    if (strtok(s," \t")==NULL) {
        return 1;
    } else {
        return 0;
    }
}

void demo(void) {
    char s1[128];
    char s2[128];
    strcpy(s1,"   abc  \t ");
    strcpy(s2,"    \t   ");
    printf("s1 = \"%s\"\n", s1);
    printf("s2 = \"%s\"\n", s2);
    printf("is_whitespace(s1)=%d\n",is_whitespace(s1));
    printf("is_whitespace(s2)=%d\n",is_whitespace(s2));
}

int main() {
    char url[63] = {'\0'};
    do {
        printf("Enter a URL: ");
        scanf("%s", url);
        printf("url='%s'\n", url);
    } while (is_whitespace(url));
    return 0;
}
nathanielng
  • 1,645
  • 1
  • 19
  • 30