如果输入(整数)为空,C 忽略 "Enter"-Key

标签 c

我一直在搜索问题,但从未找到问题的答案。 我遇到了一个问题,当您等待使用 scanf 的整数输入时,但在写入任何整数或任何其他内容之前,您开始向“Enter”键发送垃圾邮件,它总是会换行。

我想要的只是如果你等待输入但是什么都没有写并且你按下“Enter”键那么它不应该换行,它应该保持在同一行..

到目前为止我的代码(只有一部分):

printf("\n> ");
scanf("%d", &choice);
while ((ch = getchar()) != '\n' && ch != EOF);

(选择变量声明为整数)

有了这个,我从缓冲区中清除了换行符,但它仍在下一行中跳转。我也尝试了 do-while,但当没有输入时它仍然会创建一个换行符,你按下“Enter” -键。

我希望你能帮助我。

最佳答案

每当您第一次使用 C 中的函数时,您都应该始终阅读并完全理解 the manual .这解释了原因。

根据 the manual :

Input white-space characters (as specified by isspace) shall be skipped, unless the conversion specification includes a [, c, C, or n conversion specifier.

因此您的 d 转换规范(d%d 中)是通过首先跳过尽可能多的空格来执行的。这就是记录执行 fscanf 的方式。如果您想要不同的行为,那么您必须编写一些额外的/其他代码。我已经阅读并完全理解 the manual ,甚至之前多次提到它(在回答与这个非常相似的问题时,我可以补充一下)所以我可以说你可能打算写这样的东西,以便像其他控制台一样显示你的提示:

int c;
do {
    printf("> ");
    fflush(stdout);
    c = getchar();
} while (isspace(c));

/* Check for EOF */
if (c == EOF) {
    /* XXX: Clean up resources before exiting
     * (or handling EOF however else you handle it) */
    exit(0);
}

/* Put the non-space character that terminated the loop back into stdin */
ungetc(c, stdin);

/* Check scanf success */
if (scanf("%d", &choice) == 1) {
    /* Do what you will with choice here */
}

/* Discard any remaining characters up to and including the first '\n' */
do {
    /* Some consider it poor style to put side-effects into condition expressions... */
    c = getchar();
} while (c != EOF && c != '\n');

附言如果您阅读并完全理解 the manual你可能意识到你可以使用这个而不是最后一个循环:scanf("%*[^\n]"); getchar();

关于如果输入(整数)为空,C 忽略 "Enter"-Key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26544178/

相关文章:

python - 复数和分形

c - 打印结构体和枚举的矩阵

c - 为什么我不能从数组中读取数据?

c - 将 7 个字符放入 2 个 unsigned short 的数组中

检查字符串是否是 C 中的有效枚举

c - 我怎么知道c中指针变量的分配内存大小

c - 为内联汇编参数打开即时值传播的特定 GCcflags是什么?

CMake 无法正确链接库

c++ - 如何在 Windows 上紧密打包结构?

c++ - 用于模式识别/图像处理的 C 或 C++?