I need help on a problem on C programming. I was wondering if there is a way to have a user input a word to the console and it would display whatever you program it to. Heres a example of what I want to do
int Choice;
int Energy = 100;
printf ("Type 2817!\n");
scanf ("%s", &Choice);
if(Choice == 2817)
{
printf ("You have started the game\n\n\n\n\n\n\n\n\n\n\n");
}
else if(Choice == "Energy") //This isnt working in my compiler.
//Apparently the == sign is the underlined error
{
printf("%d", Energy);
}
So far I can only type numbers but I want to be able to type words and be able to use a command. SO basically I want to be able to type "Energy" and it will show the amount of energy you have (printf ("%d", Energy)
Please help,
Thank you for reading.
I'm not sure what your program is trying to do, but let me concentrate on the few obviously incorrect lines.
First, in
int Choice;
scanf ("%s", &Choice);
you have the wrong type for Choice: it is "int" whereas it should be a static array of char (let's say char Choice[32]). In this case you also have to remove the "&" before "Choice" in the scant, so that the code becomes:
char Choice[32];
scanf ("%s", Choice);
Moreover, in
else if(Choice == "Energy") //This isnt working in my compiler.
you are trying to compare two strings with the operator "==". This does not work in C. You should use the function "strcmp" the following way:
#include<string.h>
[...]
else if(strcmp(Choice, "Energy")==0)
You'd even better use the following to prevent any buffer overflow
else if(strncmp(Choice, "Energy", 32)==0)
(replace 32 with the maximum number of elements in Choice)
Edit Note that you should change the first comparison too from
if(Choice == 2817)
to
if(strncmp(Choice, "2817", 32))
because Choice is not an int anymore...