扫描 C 代码中的不同位置

  • 本文关键字:位置 代码 扫描 c
  • 更新时间 :
  • 英文 :


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 转换说明符。

  1. %d格式说明符将跳过前面的输入换行符 (n)。这就是为什么它在第一种情况下有效(首先读取运算符的情况)。

  2. scanf在输入缓冲区中保留一个换行符,在第一个scanf之后n

  3. 第二个scanf将从输入缓冲区读取额外的n到变量Operator。 这就是为什么它不起作用的原因。

  4. 由于格式说明符%c,因此不会跳过换行符。

  5. 解决方案:使用scanf(" %c", &Operator);。在开头添加额外的空格。

最新更新