C scanf奇怪的行为

时间:2017-06-30 10:43:52

标签: c scanf

我在给定代码中遇到问题,输入(2 X++ X++)会产生输出(2 0),或者任何输入都会产生(n 0)而不是(n n)。任何人都可以解释这种行为的原因吗?

#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;
}

2 个答案:

答案 0 :(得分:5)

operation被定义为3个字符长 - 也就是说,两个&#34;数据&#34;字符加上空终止符。你读了一个字符串是三个&#34;数据&#34;字符很长,但你已经忘记了空终止符。

也就是说,你的记忆可能是这样的:

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

然后你读了&#34; X ++&#34;使用其null终止符,您的内存读取:

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

需要在为'\0'分配的空间中考虑最终operation

答案 1 :(得分:-1)

    //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;
    }