如何在C中使用scanf读取三个变量?

问题描述 投票:0回答:1

我正在写一个简单的计算器。我想读取第一个整数并将其保存在el1中。然后我要打印“输入el2:\ n”,然后读取第二个整数并将其保存在el2中。之后,我需要打印“从(+,-,/,*)中选择”并阅读并将其保存在op [0]中。我的程序正在打印Enter el1 :,然后等待我输入2个整数,然后提示输入el2 :,并等待我输入1个整数,然后打印Choice from ..,什么都没读。

int el1 = 0;
printf("Enter el1:  \n");
scanf(" %d \n", &el1);
int el2 = 0;
printf("Enter el2: \n");
scanf(" %d \n", &el2);
printf("Choose from ( + ,  - ,  / , * ):\n");
char op[2];
scanf("%c", &op[0]);

如何使其正常工作?

c variables input scanf
1个回答
1
投票

如注释中所述,从scanf中删除空格。

scanf(" %c", &op[0]);处添加一个空格,因为它防止scanf将缓冲区中的\n用作输入。

外观

printf("Enter el1:  \n");
scanf("%d", &el1);
int el2 = 0;
printf("Enter el2: \n");
scanf("%d", &el2);
printf("Choose from ( + ,  - ,  / , * ):\n");
char op[2];
scanf(" %c", &op[0]);
© www.soinside.com 2019 - 2024. All rights reserved.