C: scanf() 挂起,getchar() 无法清除输入
C: scanf() hanging, getchar() not working to clear input
该函数应该提示用户输入,然后 return 一个值,但它一直挂起。
#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() 的某些部分的一部分。
您正在使用代码 %d
读取输入,但您要求将其放入 char
类型的变量中 - 该变量太小。如果将 char input
更改为 int input
,它会起作用:https://ideone.com/KpLH25
该函数应该提示用户输入,然后 return 一个值,但它一直挂起。
#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() 的某些部分的一部分。
您正在使用代码 %d
读取输入,但您要求将其放入 char
类型的变量中 - 该变量太小。如果将 char input
更改为 int input
,它会起作用:https://ideone.com/KpLH25