当 scanf 需要一个 int 但接收到字符时如何防止菜单出现故障 (C)

发布于 2024-10-21 23:08:53 字数 309 浏览 1 评论 0原文

举个例子:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜吻♂芭芘 2024-10-28 23:08:53

考虑使用 fgetssscanf 代替。加载一行的输入,然后仅解析该行而不是整个标准输入。

Consider using fgets and sscanf instead. Load a line's worth of input, then parse only that line instead of the entire stdin.

感情旳空白 2024-10-28 23:08:53

检查 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 an int 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/

陌路黄昏 2024-10-28 23:08:53

不读取整数,而是读取字符串并将其转换为数字(atoi)。可能出现的两个问题:

  1. 字符缓冲区不够大。为了防止这种情况,您可以从输入中逐个字符读取并在必要时重新分配缓冲区。
  2. 字符串不是数字。 Atoi 会返回一些默认值(0 或 -1,不记得了)。你只需要以某种方式检查字符串。

Instead of reading an integer, just read a string and convert it to a number (atoi). Two problems that may occur:

  1. Char buffer not big enough. To prevent this you can read char by char from the input and realloc the buffer if necessary.
  2. String is not a number. Atoi will return some default value (0 or -1, don't remember). You just have to check the string somehow.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文