这是我的代码:
#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 itemn4. quitn");
scanf("%dn", &op);
switch (op)
{
case 1:
add_item(&idx);
break;
case 4:
return 0;
default:
printf("Please enter a correct numbern");
}
}
}
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 memoryn");
}
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
是我输入的。
在scanf((问题之前,我已经尝试了C/C++ printf((中的解决方案,但没有一个对我有用。
您的问题出在这一行:
scanf("%dn", &op);
这里的n
只是一个空格字符(like和
scanf()
(,n
对任何空格字符都一视同仁:它们匹配输入流中任意长度(包括0(的空格序列。
如果您输入一个数字并按回车键,您确实输入了一个换行符,并且该换行符确实与t
匹配,它也将被匹配或
scanf()
。但是您不想匹配它:默认情况下,scanf()
是行缓冲的,并且由于add_item()
可以选择匹配更多空格字符,因此它将等待更多输入以查看后面是否包含更多空格,并且仅在再次按 Enter 后返回,因为使用行缓冲,输入仅在换行符处可用。
简而言之:在您再次按回车键之前,此n
不会完成,因此在您这样做之前甚至不会调用CC_13。
这里的简单解决方案:从格式字符串中删除虚假CC_14。