gpt4 book ai didi

C/C++ printf() 和 scanf() 运行程序时颠倒

转载 作者:行者123 更新时间:2023-11-30 14:55:47 25 4
gpt4 key购买 nike

这是我的代码:

#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中的解决方案但它们都不适合我。

最佳答案

您的问题在这一行中:

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

这里的 \n 只是一个空白字符(如 \t)和 scanf() 以相同方式对待任何空白字符:它们匹配输入流中任意长度(包括 0)的空白序列

如果你输入一个数字并按回车键,你确实输入一个换行符,并且这个换行符确实与 \n 匹配,它也会与 匹配\t。但您不想想要匹配它:stdin 默认情况下行缓冲,并且为 scanf()可以选择匹配更多空白字符,它将等待更多输入以查看后面是否有更多空白,并且只有在您再次按回车键时才返回,因为使用行缓冲,输入只会变成可在换行符处使用。

简而言之:除非您再次按 Enter 键,否则 scanf() 不会完成,因此在您完成之前甚至不会调用 add_item()

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

关于C/C++ printf() 和 scanf() 运行程序时颠倒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45528929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com