【问题标题】:C: scanf() hanging, getchar() not working to clear inputC:scanf() 挂起,getchar() 无法清除输入
【发布时间】:2021-03-16 03:41:47
【问题描述】:

该函数应该提示用户输入,然后返回一个值,但它一直挂起。

#include <stdio.h>

int foo(void) {
    printf("return something ");
    char input;
    scanf("%d", &input);
    while (getchar() != '\n') {}
    printf("input: %d\n", input);
    return input;
}

int main()
{
    int t = foo();
    printf("foo() returned: %d\n", t);
    return 0;
}

输出

return something 4                                                                                                     
input: 4                                                                                                               
foo() returned: 4                                                                                                      
Segmentation fault                                                                                                     
                                                                                                                       
                                                                                                                       
...Program finished with exit code 139                                                                                 
Press ENTER to exit console.   

我也尝试过 scanf(" %d", &choice) ,但无济于事。如果相关,则此代码是最终编译成 .o 文件然后链接到调用它的 main() 的某些内容的一部分。

【问题讨论】:

  • Can't reproduce。请提供complete minimal verifiable example 并显示您的确切运行日志。
  • @kaylum#include int foo(void) { printf("return something "); char input; scanf("%d", &amp;input); while (getchar() != '\n') {} printf("input: %d\n", input); return input; } int main() { int t = foo(); printf("foo() returned: %d\n", t); return 0; }
  • 不要把代码放在评论里,更新你的问题
  • @lxop 刚刚做了,我的错
  • 您的编译器肯定会发出类似于以下内容的警告:warning: format specifies type 'int *' but the argument has type 'char *' [-Wformat] scanf("%d", &amp;input);

标签: c input scanf getchar


【解决方案1】:

您正在使用代码%d 读取输入,但您要求将其放入char 类型的变量中 - 该变量太小。如果您将 char input 更改为 int input 它可以工作:https://ideone.com/KpLH25

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多