mercredi 30 septembre 2020

How to use switch statement to assign a string value to a variable

I hope that I put a title that properly relates to my problem.

The purpose of my program is to calculate the expenses for a trip between various cities. The program will give a list of source cities, followed by a list of destination cities. The user will be allowed to choose their cities by inputting the first letter of each city.

I want the program to be able to take the input from the user and assign it to one of the given cities.

//Declarations
    char src_city[15];
    char dest_city[15];
system("cls");
    puts("\n");
    printf("ENTER THE SOURCE CITY: \n\n");
    printf("B for Baltimore\n\n");
    printf("C for Chattanooga\n\n");
    printf("N for Nashville\n\n");
    printf("P for Pasadena\n\n");
    puts("");
    scanf("%c", &src_city);
    switch(src_city)
    {
    case 'B': case 'b': ("Baltimore");
    break;
    case 'C': case 'c': ("Chattanooga");
    break;
    case 'N': case 'n': ("Nashville");
    break;
    case 'P': case 'p': ("Pasadena");
    break;
    }
    getchar();

The 'B', 'C', 'N', and 'P' are the letters I want the user to input, and when they do to assign it to the corresponding city.

However, when I use this method I get the error: "assignment to expression with array type". I looked up this error and I was then told to use if/else if statements which in turn failed similarly. The switch statement method makes the most sense to me.

I need to assign the string value to the corresponding variable (src_city/dest_city) because I will need to call those variables later in a printf(); statement.

Any help would be very much appreciated!

Aucun commentaire:

Enregistrer un commentaire