0

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);
}
0

4 Answers 4

4

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

if (!strcmp(str, "\n"))
Sign up to request clarification or add additional context in comments.

2 Comments

This fails if ctrl-d is used, or if input is being redirected from a file. The correct solution would be to trim whitespace from the input and then check for an empty string.
In a sense this is a correct answer, but it misses a big issue for beginners in C: using scanf instead of a safe replacement like fgets. I'll upvote if you edit to include a discussion of why scanf is bad.
2

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);

Comments

1

%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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.