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!");
}
}
}
You cannot compare strings using
==
( You can, but it actually compares pointers and not the actual content ). But your attempt of comparing looks awkward. Usestrcmp
fromstring.h
It returns 0 if both its arguments hold the same content.So change
to
and don't forget to
#include <string.h>
!Here is an explanation of what you were doing.
Here:
there is some condition and and
if
. You know what anif
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 offirst_Pc
, achar(*)[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 notNULL
, the condition becomes true and theif
executes.