user667430
user667430

Reputation: 1547

c Exit if string is empty

I have the below code which is supposed to exit if the provided user input is empty i.e they press [ENTER] when asked for the input. However it doesnt do anything if [ENTER] is pressed.

printf("Enter the website URL:\n");
scanf("%s", str);
if(strlen(str) == 0) {
    printf("Empty URL");
    exit(2);
}

Upvotes: 0

Views: 1466

Answers (4)

Richard J. Ross III
Richard J. Ross III

Reputation: 55543

I use a isempty function:

int isempty(const char *str)
{
    for (; *str != '\0'; str++)
    {
        if (!isspace(*str))
        {
           return 0;
        }
    }

    return 1;
}

Also, I would recommend using fgets over scanf, as scanf is unsafe and can lead to buffer overflows.

fgets(str, /* allocated size of str */, stdin);

Upvotes: 2

FatalError
FatalError

Reputation: 54551

%s with scanf() will discard any leading whitespace, of which it considers your Enter keypress. If you want to be able to accept an "empty" string, you'll need to accept your input in another way, perhaps using fgets():

printf("Enter the website URL:\n");
fgets(str, SIZE_OF_STR, stdin);
if(!strcmp(str,"\n")) {
    printf("Empty URL");
    exit(2);
}

Keep in mind the above code does not consider EOF, which would leave str unchanged.

Upvotes: 1

orustammanapov
orustammanapov

Reputation: 1862

shouldn't you check for '\n' - new line? Enter will represented as a new line character '\n'

Upvotes: 0

Ismail Badawi
Ismail Badawi

Reputation: 37177

If the user just presses enter, the input will still contain a newline ('\n'). Your condition should be

if (!strcmp(str, "\n"))

Upvotes: 4

Related Questions