Jad Driggers
Jad Driggers

Reputation: 15

if statement in C

Going through some entry level C programming and having trouble with this seemingly very simple logical operator. The first if statement is skipped if you enter last name Paul. Also trying to understand buffer size when using scanf_s.

int main(){

    char name[25];

    printf("what is your last name? ");
    printf("(Please capitalize the first letter!)\n");
    scanf_s(" %s", name, 2); 

    if ((name[0] >= 'P') && (name[0] <= 'S'))

    {
        printf("You must go to room 232 for your tickets\n ");
    }
    else
    {
        printf("You can get your tickets in the lobby\n");

    }
    return 0;
}

Upvotes: 1

Views: 115

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51904

In your scanf_s(" %s", name, 2); statement, the third argument here specifies the size of the character array (name) into which to read the given response. I'm not sure why you have given 2 as that size, when you have declared, in the char name[25]; line, that you have an actual size of 25.

However, with that 2 value, the read will fail if you type in more than one character (try just giving "P" as input, and you will enter the if block).

From the documentation for scanf_s (bolding mine):

The buffer size includes the terminal null. You can use a width specification field to ensure the token that's read in fits into the buffer. When a token is too large to fit, nothing is written to the buffer unless there's a width specification.

Also, it is always a good idea to check the return value from scanf_s (and related functions), to make sure the read was successful! Adding a few check as shown in the snippet below will show you what's going on, with various different inputs:

//...
    int n = scanf_s(" %s", name, 2);
    printf("Items read = %d; Name given is: %s ...\n", n, name);
//...

With this, when I enter "Paul" as input, I see the following:

what is your last name? (Please capitalize the first letter!)
Paul
Items read = 0; Name given is:  ...
You can get your tickets in the lobby

Note: On the debate about whether or not to use scanf_s in place of scanf (as the Microsoft compiler advises), see here: Difference between scanf and scanf_s.

Upvotes: 2

Related Questions