C:键盘的多个输入

C: Multiple input from keyboard

我正在尝试从键盘读取多个输入并将输入存储在变量中。

我的代码片段:

char answer = 'N';
int artnr;
char artname [27];
int stock;
double price;

while (answer != 'Y') {
printf("%s\n", "Enter article number:");
scanf("%d" , &artnr);
printf("%s\n", "Enter article name:");
scanf("%c" , &artname);
printf("%s\n", "Enter stock balance:");
scanf("%d" , &stock);
printf("%s\n", "Enter a price");
scanf("%f" , &price);
printf("%s\n", "Do you want to quit? (Y/N)");
scanf("%c" , &answer);
}

输出:
输入文章编号:
1
输入文章名称:
输入库存余额:
25
输入价格
4
你想戒烟吗? (Y/N)
输入文章编号:

我的扫描似乎出了点问题。我想它必须与文章名称中的 '/o' 或当我按下 enter 以确认我的输入时。

artname 是一个字符数组,"Enter article name:" 表明您实际上想要扫描一个字符串。 所以,这个

scanf("%c" , &artname);

可能应该是

scanf("%s", artname);
当您在输入缓冲区中使用 %c 扫描时,

scanf() 会留下尾随的换行符。您可以通过在格式字符串中添加一个空格来忽略它:

scanf("%c" , &answer);

scanf(" %c" , &answer); // Notice the space in " %c"

格式字符串中的空格告诉 scanf() 忽略输入中任意数量的空格。

并更改此

scanf("%f" , &price); 

scanf("%lf" , &price);

为了匹配格式字符串与类型。