0

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?

Saxtheowl
  • 4,136
  • 5
  • 23
  • 32
CosmicCat
  • 612
  • 9
  • 19

1 Answers1

3

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Gyapti Jain
  • 4,056
  • 20
  • 40
  • 1
    *There were 2 problems.* **Three** problems - the return value from `scanf()` is never checked to make sure something is actually read from the console. – Andrew Henle Oct 01 '19 at 09:47
  • Thanks so much! So why does the space make such a big difference? As a new C programmer, I wouldnt even know where to start looking to solve such a small problem... – CosmicCat Oct 01 '19 at 23:34
  • @CosmicCat [Space makes a difference when you are reading a `char` with `%c`](https://stackoverflow.com/questions/6582322/what-does-space-in-scanf-mean) because space is also a `char`. When you specify a space you ask `scanf` to skip every white space character (space, tab, newline etc) and read the first non white space character. Without space you ask for first character that may or may not be a white space. To solve such problems, you can read specifications of functionalities used for ex. `scanf` in this case from man page or good book and solve some toy problems. – Gyapti Jain Oct 03 '19 at 04:40