简体   繁体   English

C 程序在接受 scanf() 输入之前终止

[英]C program terminates before accepting scanf() input

Although I understand the layout of this program is wierd, I think my program is having trouble when it comes to the scanf() line.虽然我知道这个程序的布局很奇怪,但我认为我的程序在涉及到scanf()行时遇到了问题。 For some reason after the metricConversion() function is entered.由于某种原因,在输入metricConversion() function 之后。 The scanf() line is printed but the program exits and terminates before an input is given... I am not understanding why this happens...打印了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();
    }
}

More importantly, can someone explains why scanf() works the way it does?更重要的是,有人能解释一下为什么scanf()会这样工作吗? And what the best alternatives are so I dont run into this again?最好的选择是什么,所以我不会再遇到这种情况了?

Change scanf("Press K for conversion from Kelvin to Celsius %c", &inputtedChar);更改scanf("Press K for conversion from Kelvin to Celsius %c", &inputtedChar); to:至:

printf("Press K for conversion from Kelvin to Celsius ");
fflush(stdout);
scanf(" %c", &inputtedChar);
/*     ^                    */
/*   this space             */

There were 2 problems.有2个问题。 Use printf for prompt.使用printf进行提示。 And you need to use space in scanf to ignore whitespace before a %c , %[…] (scan set) or %n conversion.并且您需要在scanf中使用空格以在%c%[…] (扫描集)或%n转换之前忽略空格。 Using fflush will ensure that the prompt is printed on screen before it waits for input.使用fflush将确保在等待输入之前将提示打印在屏幕上。

It is advisable to use an fflush before scanf in main function also unless you want to terminate printed string with a '\n' .建议在main function 中的scanf之前使用fflush ,除非您想用'\n'终止打印的字符串。


What does scanf("Press K for conversion from Kelvin to Celsius %c", &inputtedChar); scanf("Press K for conversion from Kelvin to Celsius %c", &inputtedChar); mean?意思是?

This doesn't print anything.这不会打印任何东西。 It means program expects exact input Press K for conversion from Kelvin to Celsius <SOME_CHAR> and reads <SOME_CHAR> in input.这意味着程序需要精确的输入Press K for conversion from Kelvin to Celsius <SOME_CHAR>并在输入中读取<SOME_CHAR> For more details you need to understand the regex.有关更多详细信息,您需要了解正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM