虽然我知道这个程序的布局很奇怪,但我认为我的程序在处理 scanf()
行时遇到了问题。由于某种原因,在输入 metricConversion()
函数后。 scanf()
行已打印,但程序在给出输入之前退出并终止...我不明白为什么会发生这种情况...
#include <stdio.h>
char inputtedChar;
int inputtedInt;
int metricConversion(){
scanf("Press K for conversion from Kelvin to Celsius %c", &inputtedChar);
if(inputtedChar == 'K'){
//do Something
} else { return 0; }
}
int main() {
printf("Press 0 to enter conversion function!");
scanf("%d", &inputtedInt);
if (inputtedInt == 0) {
metricConversion();
}
}
更重要的是,有人可以解释为什么 scanf()
会这样工作吗?最好的替代方案是什么,这样我就不会再遇到这个问题了?
最佳答案
更改 scanf("Press K for conversion from Kelvin to Celsius %c", &inputtedChar);
到:
printf("Press K for conversion from Kelvin to Celsius ");
fflush(stdout);
scanf(" %c", &inputtedChar);
/* ^ */
/* this space */
有两个问题。使用 printf
提示。你需要在scanf
中使用空间忽略 %c
之前的空格, %[…]
(扫描集)或 %n
转换。使用 fflush
将确保在等待输入之前将提示打印在屏幕上。
建议使用 fflush
之前scanf
在main
功能也一样,除非你想用 '\n'
终止打印的字符串.
What does
scanf("Press K for conversion from Kelvin to Celsius %c", &inputtedChar);
mean?
这不会打印任何内容。这意味着程序需要准确的输入 Press K for conversion from Kelvin to Celsius <SOME_CHAR>
并阅读 <SOME_CHAR>
在输入。有关更多详细信息,您需要了解正则表达式。
关于C 程序在接受 scanf() 输入之前终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58179073/