Jan Lovšin
Jan Lovšin

Reputation: 3

C scanf weird behaviour

I've a problem in the given code that inputting (2 X++ X++) will produce output (2 0), or any input will produce (n 0) instead of (n n). Can anyone explain the reason for this behavior?

#include <stdio.h>

int main()
{
    int n;
    scanf("%d", &n);
    int number = 0;
    for (int i = 0; i < n; i++)
    {
        char operation[3];
        printf("%d\n", n);
        scanf("%s", operation);
        printf("%d\n", n);
        if (operation[0] == '+' || operation[2] == '+')
            number++;
        else
            number--;
    }

    return 0;
}

Upvotes: 0

Views: 347

Answers (2)

Bicolano
Bicolano

Reputation: 90

    //I hope this will help you.

    //You can just improve this the way you want your program to run


    #include <stdio.h>

    int main()
    {
        int n;
        scanf("%d", &n);
        int number = 0;

        for(int i = 0; i < n; i++)
        {
            char operation[4];//please make this [4] to reserve space for '\0' or the NULL character.

            printf("loop %d: ", i + 1);//this checks the number of loop.
            scanf("%s", operation);

            //Use && operator instead of || operator to test both expression if it's both a '+' character. If you use ||, The result will be true even either one of [1] or [2] have 'x'. And I know that's not the result you want.
            if (operation[1] == '+' && operation[2] == '+')//test in operation[1] and operation[2] instead in operation[0] because what's in operation[0] is not a '+' but 'x'.
                number++;
            //same here. Use && operator.
            else if(operation[1] == '-' && operation[2] == '-')//same here. And don't just leave it in "else". make this an "else if" statement to make sure the user enters "x--" before you decrement the value of the "number"
                number--;
            /*else, do nothing to "number"*/

            printf("number is now: %d\n\n", number);
        }

        return 0;
    }

Upvotes: -1

Chowlett
Chowlett

Reputation: 46657

operation is defined to be 3 characters long - that is, two "data" characters plus the null terminator. You read into it a string that is three "data" characters long, but you've forgotten the null terminator.

That is, your memory probably looks like this:

+---+---+---+---+
|   |   |   | 2 |
+---+---+---+---+
<-operation-> n

Then you read in "X++" with its null terminator, and your memory reads:

+---+---+---+---+
| X | + | + | \0|
+---+---+---+---+
<-operation-> n

That final '\0' needs to be accounted for in the space allocated for operation.

Upvotes: 5

Related Questions