[英]C/C++ printf() and scanf() reversed when running the program
这是我的代码:
#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
是我输入的。)
我在scanf()问题之前尝试过C / C ++ printf()中的解决方案,但它们都不适合我。
您的问题在这一行:
scanf("%d\n", &op);
\\n
只是一个空白字符 (例如 和
\\t
)和scanf()
对待任何空白字符:它们匹配任意长度(包括0)的输入流中的空白序列 。
如果输入数字并按Enter键, 则输入一个换行符,并且该换行符确实由\\n
匹配,也将由\\n
匹配。 或
\\t
。 但是您不想匹配它:默认情况下, stdin
是行缓冲的 ,并且scanf()
可以选择匹配更多的空白字符,它将等待更多的输入来查看是否有更多的空白,并且只有在再次按下Enter键后才返回因为使用行缓冲 ,输入仅在换行符处可用。
简而言之:直到再次按下回车键,此scanf()
才会完成,因此,直到您再次点击add_item()
为止。
这里的简单解决方案是:从格式字符串中删除假冒\\n
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.