当 scanf 需要一个 int 但接收到字符时如何防止菜单出现故障 (C)
举个例子:
printf("Continue?\n>>");
scanf("%d", &cont);
getchar();
通常我添加 getchar() 来防止程序无限循环(从缓冲区读取 '\n' 字符)。但是,当与此语句后面的菜单一起使用时,会读入额外的字符,并且会跳过字符输入后面的任何 scanfs(最多为输入的字符数)。
我想弄清楚的是,当它读取除 int 之外的输入类型时,如何防止它向前跳过程序的几个部分。最好的解决方法是将其放入一个循环中,直到变量位于预期域中为止,该循环才会继续吗?
Take for instance:
printf("Continue?\n>>");
scanf("%d", &cont);
getchar();
Normally I add the getchar() to prevent the program from infinite looping (reading off the '\n' character from the buffer). However, when used with a menu following this statement the extra characters are read in and any scanfs following the character input (up to the number of characters input) are skipped.
What I want to figure out is how to prevent it from skipping forward through several sections of my program when it reads in a type of input other than an int. Would this be best solved by putting it inside of a loop that won't continue until the variable is in the expected domain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑使用
fgets
和sscanf
代替。加载一行的输入,然后仅解析该行而不是整个标准输入。Consider using
fgets
andsscanf
instead. Load a line's worth of input, then parse only that line instead of the entire stdin.检查
scanf
返回的值。返回值指示分配给的数字变量。如果您需要int
并且用户输入字符,则scanf
应返回零。尝试包含
"%*s"
输入说明符。请参阅http://www.cplusplus.com/reference/clibrary/cstdio/scanf/< /a>Check the value returned by
scanf
. The return value indicates the number variables that were assigned to. If you're expecting anint
and the user types in a character,scanf
should return zero.Try including a
"%*s"
input specifier. See http://www.cplusplus.com/reference/clibrary/cstdio/scanf/不读取整数,而是读取字符串并将其转换为数字(atoi)。可能出现的两个问题:
Instead of reading an integer, just read a string and convert it to a number (atoi). Two problems that may occur: