运行程序时,C / C ++ printf()和scanf()反转

时间:2017-08-06 05:39:16

标签: c printf scanf

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
enum abcd{aaaa,bbbb,cccc,dddd,z};

typedef struct stct{
    abcd eAbcd;
    int x;
} stct;
typedef struct indexx{
    int size;
    struct stct *addr;
} indexx;

void add_item(indexx *idx);
stct read_in();

int main()
{
    indexx idx = {0, NULL};
    int op;
    while (1)
    {
        printf("\n1. add item\n4. quit\n");
        scanf("%d\n", &op);
        switch (op)
        {
            case 1:
                add_item(&idx);
                break;
            case 4:
                return 0;
            default:
                printf("Please enter a correct number\n");
        }
    }
}

void add_item(indexx *idx)
{
    stct *newdata;
    newdata = (stct *) realloc(idx->addr, idx->size*sizeof(stct));
    if (newdata)
    {
        idx->size ++;
        idx->addr = newdata;
        idx->addr[idx->size-1] = read_in();
    }
    else
        printf("No memory\n");
}

stct read_in()
{
    stct temp;
    int ab;
    temp.eAbcd = z;
    while (temp.eAbcd != aaaa && temp.eAbcd != bbbb && temp.eAbcd != cccc && temp.eAbcd != dddd)
    {
        printf("select(1-4):\n");
        scanf("%d", &ab);
        ab-=1;
        switch (ab)
        {
            case 0: temp.eAbcd = aaaa; break;
            case 1: temp.eAbcd = bbbb; break;
            case 2: temp.eAbcd = cccc; break;
            case 3: temp.eAbcd = dddd; break;
        }
    }
    scanf("%d", &temp.x);
    return temp;
}

它应该在scanf()之前打印出select(1-4):,但是当我编译并运行程序时,我得到了这个:

1
select(1-4):

1就是我输入的内容。)

我已经尝试了C/C++ printf() before scanf() issue中的解决方案,但它们都不适用于我。

1 个答案:

答案 0 :(得分:1)

您的问题出在行:

    scanf("%d\n", &op);

这里的\n只是空格字符(例如\t),而scanf()会将任何空白字符视为相同:匹配任意长度(包括0)的输入流中的空格的序列

如果您输入一个数字并按Enter键,执行输入换行符,此换行符确实与\n匹配,它也会被或{匹配{1}}。但是你没有想要来匹配它:\t默认为行缓冲,而stdin可选择匹配更多空白字符,等待以获取更多输入,以查看是否有更多空格跟随并且只有在您再次按Enter后才返回,因为行缓冲,输入仅在换行时可用。< / p>

简而言之:scanf()这个scanf()一直没有完成,直到你再次点击输入为止,所以add_item()甚至不会被调用,直到你这么做。

此处的简单解决方案:从格式字符串中删除伪造的\n