![](/img/trans.png)
[英]Basic c program doesn't continue after the final scanf in the function, scanf just keeps accepting input endlessly
[英]C program terminates before accepting scanf() input
虽然我知道这个程序的布局很奇怪,但我认为我的程序在涉及到scanf()
行时遇到了问题。 由于某种原因,在输入metricConversion()
function 之后。 打印了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 */
有2个问题。 使用printf
进行提示。 并且您需要在scanf
中使用空格以在%c
、 %[…]
(扫描集)或%n
转换之前忽略空格。 使用fflush
将确保在等待输入之前将提示打印在屏幕上。
建议在main
function 中的scanf
之前使用fflush
,除非您想用'\n'
终止打印的字符串。
scanf("Press K for conversion from Kelvin to Celsius %c", &inputtedChar);
意思是?
这不会打印任何东西。 这意味着程序需要精确的输入Press K for conversion from Kelvin to Celsius <SOME_CHAR>
并在输入中读取<SOME_CHAR>
。 有关更多详细信息,您需要了解正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.