gpt4 book ai didi

c - scanf 和输入字符

转载 作者:行者123 更新时间:2023-11-30 20:49:26 25 4
gpt4 key购买 nike

我想知道如果在我的程序中我要求使用 scanf("%d",&num) 进行整数输入,会发生什么情况?用户输入一串字符和整数,例如 at3stf0rfunnum 的值是多少在这种情况下?是否只需要整数 30或者它是否也将字符转换为其 ASCII 十进制值?

最佳答案

扫描在遇到无效输入时停止。因此,在您的代码中,num 的值将保持不变。

要检测是否发生了这种情况,您需要检查 scanf 的返回值。引用 man scanf:

RETURN VALUES

These functions return the number of input items assigned. This can be fewer than provided for, or even zero, in the event of a matching failure. Zero indicates that, although there was input available, no conversions were assigned; typically this is due to an invalid input character, such as an alphabetic character for a `%d' conversion. The value EOF is returned if an input failure occurs before any conversion such as an end-of-file occurs. If an error or end-of-file occurs after conversion has begun, the number of conversions which were successfully completed is returned.

关于c - scanf 和输入字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15874424/

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