gpt4 book ai didi

c - 为什么在 C 编程中 scanf ("%d", &number) 结果 'a' 为 29?

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:21 24 4
gpt4 key购买 nike

我在 C 中有以下代码

#include <stdio.h>
int main()
{
int number;

// printf() displays the formatted output
printf("Enter an integer: ");

// scanf() reads the formatted input and stores them
scanf("%d", &number);

// printf() displays the formatted output
printf("You entered: %d", number);
return 0;
}

在这里我应该输入一个数字,但我输入了一个字符“a”,结果是 29。我预计它会抛出异常,但我对输出感到惊讶。 Screen shots of an output of the program.

最佳答案

对于初学者来说,不带参数的函数 main 应该像这样声明

int main( void )

只需按以下方式更改您的程序

#include <stdio.h>

int main( void )
{
int number;

// printf() displays the formatted output
printf("Enter an integer: ");

// scanf() reads the formatted input and stores them
if (scanf("%d", &number) == 1)
{
// printf() displays the formatted output
printf("You entered: %d\n", number);
}
else
{
puts("Invalid input");
}

return 0;
}

如果您尝试输入字符 'a' 而不是数字,看看会发生什么。

根据C标准中函数的描述(7.21.6.2 fscanf函数)

d Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with
the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer.

以及(7.22.1.4 strtol、strtoll、strtoul 和 strtoull 函数)

7 If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

因此在演示程序中将执行 else 语句,因为(C 标准,7.21.6.2 fscanf 函数)

16 The fscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure

关于c - 为什么在 C 编程中 scanf ("%d", &number) 结果 'a' 为 29?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47972360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com