在控制台应用程序中获取 int 的最简单方法是什么?
我想将用户输入作为整数处理,但似乎 C 无法从 stdin 获取 int 。 有一个函数可以做到这一点吗? 我将如何从用户那里获取 int ?
I want to process user input as an integer, but it seems as though C has no way to get an int from stdin. Is there a function to do this? How would I go about getting an int from the user?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请参阅http://www.cplusplus.com/reference/clibrary/cstdio/scanf/< /a>
See http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
scanf()
是答案,但您当然应该检查返回值,因为从外部输入解析数字时,很多很多事情都可能会出错......scanf()
is the answer, but you should certainly check the return value since many, many things can go wrong parsing numbers from external input...除了其他答案已经充分讨论的 (f)scanf 之外,还有
atoi
和strtol
,适用于您已经已将输入读取到字符串中,但希望将其转换为int
或long
。推荐使用
strtol
,因为它可以让你判断一个数字是否被成功读取(与atoi
不同,后者无法报告任何错误,只会返回如果给出垃圾则为 0)。Aside from
(f)scanf
, which has been sufficiently discussed by the other answers, there is alsoatoi
andstrtol
, for cases when you already have read input into a string but want to convert it into anint
orlong
.strtol
is recommended because it allows you to determine whether a number was successfully read or not (as opposed toatoi
, which has no way to report any error, and will simply return 0 if it given garbage).标准库函数 scanf 用于格式化输入:
%d int(d 是十进制的缩写)
The standard library function scanf is used for formatted input:
%d int (the d is short for decimal)
来自此处
from here