Hey Guys, I am writing this program in C and it starts by a single play or quit
ID: 3637114 • Letter: H
Question
Hey Guys,
I am writing this program in C and it starts by a single play or quit statement.. now i want to go into an if statement based on what the user enters... e.g if user enter play or Play .. -> ignores case so upper or lower is fine... do something ... else terminate the program.
Here is my code snippet
printf("Hello %s, would you like to Play or Quit? ", name);
fgets(line, sizeof(line), stdin);
i wanna do something like
if line = "Play" || play { do ....}
else { quit}
i saw strcmp but it wasnt working for me... i think my syntax may have been wrong..
any suggestions is appreciated
Explanation / Answer
please rate - thanks
2 options
change all letters to same case then use strcmp
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{char line[10],name[10];
char *in;
int i;
printf("Enter your name: ");
in=gets(name);
printf("Hello %s, would you like to Play or Quit? ", name);
in=gets(line);
for(i=0;line[i]!='';i++)
{if(isalpha(line[i]))
line[i]=toupper(line[i]);
}
while(strcmp(line,"PLAY")==0)
{//your code
printf("%s, would you like to Play or Quit? ", name);
in=gets(line);
for(i=0;line[i]!='';i++)
{if(isalpha(line[i]))
line[i]=toupper(line[i]);
}
}
return 0;
}
-------------------------------
compare 1 letter at a time
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{char line[10],name[10],play[5]="PLAY";
int allsame=1;
char *in;
int i;
printf("Enter your name: ");
in=gets(name);
printf("Hello %s, would you like to Play or Quit? ", name);
in=gets(line);
for(i=0;line[i]!='';i++)
{if(toupper(line[i])!=play[i])
allsame=0;
}
while(allsame==1)
{//your code
printf("%s, would you like to Play or Quit? ", name);
in=gets(line);
allsame=1;
for(i=0;line[i]!='';i++)
{if(toupper(line[i])!=play[i])
allsame=0;
}
}
return 0;
}