user3035890 user3035890 - 1 year ago 128
C Question

How to check if String is empty in C

I have a void function which take the string from a global variable and prints them.

The problem is that the void function prints a message/does stuff even if the string is empy.
so if the global variable is empt it just prints "message is:"
i only want to do something if the string has characters.

what i want to do is to check if the string is not empty, then print a message.

// global variable

char msg[30];
scanf("%s", &msg);

void timer(void) {
//i want to only print if there is a message
printf("message: %s", msg);

thanks for any help

Answer Source

The easy way to do it would be like this:

if (msg[0])
    printf("message: %s", msg);

If, at some later date, msg is a pointer, you would first want to assure it's not a NULL pointer.

if (msg && msg[0])
    printf("message: %s", msg);

A test program to demonstrate:

#include <stdio.h>
#include <stdlib.h>

char *msg;

void test() {
    if (msg && msg[0])
        printf("string is %s\n", msg);

int main()
    msg = NULL;
    msg = calloc(10, 1);
    msg[0] = 'm';
    msg[1] = 'e';

On my machine the output is:

string is me

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download