CosmicCat
CosmicCat

Reputation: 622

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. For some reason after the metricConversion() function is entered. The scanf() line is printed but the program exits and terminates before an input is given... I am not understanding why this happens...

#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? And what the best alternatives are so I dont run into this again?

Upvotes: 0

Views: 1116

Answers (1)

Gyapti Jain
Gyapti Jain

Reputation: 4106

Change 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. Use printf for prompt. And you need to use space in scanf to ignore whitespace before a %c, %[…] (scan set) or %n conversion. Using fflush will ensure that the prompt is printed on screen before it waits for input.

It is advisable to use an fflush before scanf in main function also unless you want to terminate printed string with a '\n'.


What does 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. For more details you need to understand the regex.

Upvotes: 3

Related Questions