How to check if a String is not in C

I have a void function that takes a string from a global variable and prints them.

The problem is the void function prints out a message / does things even if the string is empy. so if the global variable is empt, it just prints a "message:" I only want to do something if the string contains characters.

what i want to do is check if the line is empty and then print the 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

+3


source to share


5 answers


An easy way to do this would be:

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

      

If at some later date msg

is a pointer, you must first assure it is not a NULL pointer.

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

      



Trial program for demonstration:

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

char *msg;

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

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

      

On my machine, the output is:

string is me

+13


source


Strings in C are represented as arrays of characters, terminated by a character whose value is zero (often written as '\0'

). The length of the string is the number of characters that go down to zero.

So, the string is empty if the first character in the array is zero, since then, by definition, the characters did not fall to zero.

You can check it like this:



if(msg[0] != '\0')
{
  /* string isn't empty! */
}

      

This is very explicit code, shorter if(msg[0])

or if(*msg)

has the same semantics, but can be a little more difficult to read. It's mostly a matter of personal style.

Note that in your case, when you use scanf()

to read in msg

, msg

you must check the return value from before checking the content scanf()

. It scanf()

is quite possible for it to fail and then you cannot rely msg

on an empty string.

+7


source


This should work for you:

The message will only be printed if it is greater than 0.

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

void timer() {

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

    if(strlen(msg) != 0)
        printf("message: %s", msg);
}

int main() {

    timer();

    return 0; 
}

      

+3


source


Here's all I found (and can think of) to check if a string is empty. Sorted by efficiency.

  • msg[0] == '\0'

  • strlen(msg) == 0

  • !strcmp(msg, "")

And this is what should only happen if the user somehow avoided the input (for example with a Ctrl+Z) or an error occurred

  • scanf("%s", &msg) <= 0

0


source


Ok, you can try this:

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

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

      

`

-1


source







All Articles