0

I wrote a very simple program in C, but I am not getting any output. I think my functions are not being called, I tried debugging in my IDE but couldn't narrow it down as to why. Please help!!.
Here is the code

/*The distance between 2 cities (in km) is input via keyboard.WAP to 
convert & print it in meters, feet, inches and centimetres.*/

#include<stdio.h>
//function to convert & print in meters
int toMeters(int diKM)
{
    int meters;
    meters=diKM*1000;   //convert km to m
    printf("En meters, %d esta=%d",diKM,meters);
    return 0;
}
int toFeet(int diKM)
{
    float feet;
    feet=diKM*3280.84;  //convert km to feet
    printf("En feet, %d esta=%f",diKM,feet);
    return 0;
}
int toInches(int diKM)
{
    float inch;
    inch=diKM*39370.08; //convert to inch
    printf("En inch, %d esta=%f",diKM,inch);
    return 0;
}
int toCentimeters(int diKM)
{
    int cm;
    cm= diKM*100000;    //convert to cm
    printf("En centimeters, %d esta=%d",diKM,cm);
    return 0;
}
//main program
int main(){
    int km;     //store input distance in km
    //Ask & take input
    printf("How far is it?\n"); 
    scanf("%d\n",&km);
    //Call functions to convert & print input  
    toMeters(km);
    toFeet(km);
    toInches(km);
    toCentimeters(km);
    return 0;
}

There is some Spanish which I added for fun. Any suggestions regarding that are welcome too!
Thank you in advance for your valuable time.

P_K
  • 17
  • 6
  • 2
    `scanf("%d\n",&km);`-> `scanf("%d",&km);` – Some programmer dude Aug 23 '22 at 07:13
  • 1
    @DavidRanieri "Space" is *any* white-space, including newline. And it requires some non-space input to be able to continue execution. It fits with the description that the "functions are not being called". But the second one could be useful as well (you could add it as a duplicate). – Some programmer dude Aug 23 '22 at 07:26

1 Answers1

1

This line causing problem

scanf("%d\n",&km);

Because of \n it taking another input after pressing enter

White space characters in the scanf format string are directives that mean read white space characters until you get a non white space character. A trailing \n in your format string causes scanf to consume the linefeed that was typed by the user and to keep asking for input until a non white space character is seen, but is left in the input buffer. reference

How far is it?
10
10
En meters, 10 esta=10000En feet, 10 esta=32808.398438En inch, 10 esta=393700.812500En centimeters, 10 esta=1000000

removing \n will solve the problem

scanf("%d",&km);
Sidharth Mudgil
  • 1,293
  • 8
  • 25