int main()
{
char Operator;
int num1, num2, result;
/* printf("Enter operator: ");
scanf("%c", &Operator);*/
printf("Enter first and second value: ");
scanf("%d %d", &num1, &num2);
printf("Enter operator: ");
scanf("%c", &Operator);
if(Operator == '+')
{
result = num1 + num2;
printf("%dn", result);
}
else if(Operator == '-')
{
result = num1 - num2;
printf("%dn", result);
}
return 0;
}
我尝试制作一个简单的计算器,并将scanf(请求运算符的计算器)放在现在的位置,但它不起作用。但是,如果我将其放在注释所在的位置,在"输入第一个和第二个值"上方,它就可以工作了。我只想知道为什么它在一个地方工作而不是另一个地方。 提前谢谢。
正如注释中指出的,您的第一个扫描是读取整数值,但它没有读取缓冲区中的换行符。当您再次scanf("%c", &Operator)
接受字符输入时,它会读取输入缓冲区中仍然存在的换行符。为避免这种情况,您可以改用scanf(" %c", %Operator)
,这将在匹配字符之前丢弃所有空格字符:
printf("Enter operator: ");
scanf(" %c", &Operator);
还可以使用fgets()
将输入读取到字符串中,然后使用sscanf()
从字符串中读取整数:
char input[100];
printf("Enter first and second value: ");
if (fgets(input, 100, stdin) == NULL) {
printf("No input provided!n");
return -1;
}
if (strchr(input, 'n') == NULL) {
printf("Input Buffer Overflown");
return -1;
}
if (sscanf(input, "%d %d", &num1, &num2) != 2) {
printf("Error in reading charactersn");
return -1;
}
printf("Enter operator: ");
if (fgets(input, 100, stdin) == NULL) {
printf("No input provided!n");
return -1;
}
if (strchr(input, 'n') == NULL) {
printf("Input Buffer Overflown");
return -1;
}
if (sscanf(input, "%c", &Operator) != 1) {
printf("Error in reading charactersn");
return -1;
}
来自开放组基本规范问题,
输入的空格字符(由 isspace() 指定)应为 跳过,除非转换规范包含 [、c、C 或 n 转换说明符。
-
%d
格式说明符将跳过前面的输入换行符 (n
)。这就是为什么它在第一种情况下有效(首先读取运算符的情况)。 -
scanf
在输入缓冲区中保留一个换行符,在第一个scanf
之后n
。 -
第二个
scanf
将从输入缓冲区读取额外的n
到变量Operator
。 这就是为什么它不起作用的原因。 -
由于格式说明符
%c
,因此不会跳过换行符。 -
解决方案:使用
scanf(" %c", &Operator);
。在开头添加额外的空格。