0

The following program I have written immediately stops after the user enters '1' and does not complete the function kilometer_miles. What have I done wrong?

#include <stdio.h>

void kilometer_mile() {
    char inputChar;
    double kilometers = 0.0;
    double miles = 0.0;
    printf("To convert from Kilometers to Miles enter 'K'\n"
        "To convert from Miles to Kilometers enter 'M'\n");
    scanf("%c", &inputChar);
    if(inputChar == 'K') {
        printf("Enter kilometers: ");
        scanf("%c", &inputChar);
        miles = kilometers/1.609;
        printf("%lf kilometers is equal to %lf miles", kilometers, miles);
    } else if(inputChar == 'M') {
        printf("Enter miles: ");
        scanf("%c", &inputChar);
        kilometers = miles/1.609;
        printf("%lf miles is equal to %lf kilometers", miles, kilometers);
    }
}
int main() {
    int inputValue = 0;
    printf("Type 1 to convert from Kilometers to Miles\n"
        "Type 2 to convert from Meters to Feet\n"
        "Type 3 to convert from Centimetre to Inch\n"
        "Type 4 to convert from Celsius to Fahrenheit\n"
        "Type 5 to quit the program\n");
    scanf("%d", &inputValue);

    if(inputValue == 1) {
        kilometer_mile();
    }
    return 0;
}
Michael Powers
  • 1,970
  • 1
  • 7
  • 12
Ben Tilden
  • 39
  • 7
  • Have you tried adding some debug? `if (inputValue == 1) {...}else{printf("inputValue is :%d\n", inputValue);}` – Tormund Giantsbane Oct 08 '18 at 19:35
  • The newline left in the inpt buffer in `scanf("%d", &inputValue);` (in `main`) is read by `scanf("%c", &inputChar);` in the function, and so fails your tests, and the function ends without doing anything. – Weather Vane Oct 08 '18 at 19:36
  • I suggest in `scanf("%c", &inputChar);` add a space so it is `scanf(" %c", &inputChar);` which will clean off that waiting newline. Aside: you don't enter any kilometres or miles but copy-pasted the `char` input! – Weather Vane Oct 08 '18 at 19:38
  • Among other things, you never assign values to `kilometers` or `miles` after they're initialized. The `scanf` calls that should be reading those values are instead reading values for `inputChar`. – Keith Thompson Oct 08 '18 at 19:39

1 Answers1

2

The problem is you are not reading the '\n' that is also issued when the user presses enter on the first scanf function; so in your kilometer_mile function you are actually reading '\n' on your char which is not in either of the ifs given

DZDomi
  • 1,685
  • 15
  • 13