-1

I want to create a program that tells you the distance between 2 cities you choose(there are 3 cities,you can choose 2) and i wrote the code but it gives me no output after i input city1 and city2. I am a beginner and i heard about strcmp but is there another way to do it? Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>



int main()
{
char city1[] = "Zurich";
char city2[] = "Vienna";
char city3[] = "Berlin";
char location[20];
char destination[20];

puts("Which city are you in at the moment?");
gets(location);
puts("Which city do you want to go to?");
gets(destination);

if(location == city1)
{
    if(destination == city2)
    {
        printf("Distance between %s and %s is 743km and it will take you 7 hours and 40 minutes to get there", city1, city2);
    }
    else
    {
        printf("Distance between %s and %s is 844km and it will take you 8 hours and 40 minutes to get there", city1, city3);
    }   

}
else if(location == city2)
{
    if(destination == city3)
    {
        printf("Distance between %s and %s is 640km and it will take you 7 hours and 15 minutes to get there", city2, city3 );
    }
    else
    {
        printf("Distance between %s and %s is 743km and it will take you 7 hours and 40 minutes to get there", city2, city1);   
    }



}





return 0;
}
IP002
  • 471
  • 1
  • 5
  • 17

1 Answers1

1

location == city1 is comparing pointer addresses, which will not be equal.

You need to use !strcmp(location, city1) &c. instead. strcmp returns 0 if the string contents are the same.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483