I am trying to run a block of code in c but it doesn't execute the way I expect/want

93 views Asked by At

This is my code of C program. In this application I prompt user to choose any computer model from the list on the screen. If the user chooses Dell then prompt bluh bluh bluh and if user choose any other model then execute bluh bluh. Well the case is that after compiling, when I run the application, it doesn't respond the way I want. After if condition, else if and else are not executed whether if condition is not true. I too use cs50 library to get string from user which I can also do from scanf.

Here is the code.

#include <stdio.h>
#include "cs50.h"

int main (void)
{
    char first_Pc[] = "Dell"; 
    char second_Pc[] = "Intel";
    char third_Pc[] = "Max";

    {
        printf("Please Specify your choice. \n");
        printf("We have Dell, Intel And Max computers:\n");

        string userChoice = GetString();

            if ("userChoice == first_Pc", &first_Pc)
            {
                printf("Nice Choice! Your Dell worths $100.");
            }
            else if ("userChoice == second_Pc", &second_Pc)
            {
                printf("You prefer Intel computers! They are smart. You have to pay $150.");
            }
            else if ("userChoice == third_Pc", &third_Pc)
            {
                printf("Max computers are really superfast! They worth $200");
            }
            else 
            {
                printf("You didn't choose any from our stored models!");
            }
    }
}
1

There are 1 answers

4
Spikatrix On

You cannot compare strings using == ( You can, but it actually compares pointers and not the actual content ). But your attempt of comparing looks awkward. Use strcmp from string.h It returns 0 if both its arguments hold the same content.

So change

if ("userChoice == first_Pc", &first_Pc)
else if ("userChoice == second_Pc", &second_Pc)
else if ("userChoice == third_Pc", &third_Pc)

to

if (strcmp(userChoice, first_Pc) == 0)
else if (strcmp(userChoice, second_Pc) == 0)
else if (strcmp(userChoice, third_Pc) == 0)

and don't forget to #include <string.h>!


Here is an explanation of what you were doing.

Here:

if ("userChoice == first_Pc", &first_Pc)

there is some condition and and if. You know what an if does so lets skip that part. The condition here is "userChoice == first_Pc", &first_Pc. The first part is a string literal "..." (the contents in them don't matter) and the second part is the address of first_Pc, a char(*)[5], seperated by a comma operator.

The comma operator evaluates its left operand and returns the right. In this case, the string literal is evaluated and discarded and the address of first_Pc is returned. Since it is not NULL, the condition becomes true and the if executes.