== is not working

+1 put pini · October 6, 2015

I am watching Buckys C tutorial 22 right now and I tried to program that it prints out "you did a good job" if the user types into my program Y or N.
So I used if ((answer == 'Y') || (answer == 'N')) { printf("you did a good job");};
But not only if I type in Y or N but also if I type in "YAsjdifawherakjdsf" or any other stupid things it tells me that I did a good job. I thought the == means that it only prints that I did a good job if I typed exactly Y or N into the system./images/forum/upload/2015-10-06/17e65e08ecbaf76bc31214660ceea6a8.jpg
I made a screenshot so that you can convince yourself, can anyone explain me the reason for this mess?

Thank you really much!

Post a Reply


Oldest  Newest  Rating
0 Suraj Gautam · October 12, 2015
if(answer==Y || answer==y){
printf("You did good job\n"); 
printf("No good job\n");
Try this.... don't use semicolon after the curly braces in else....
0 Linguist Llama · October 15, 2015
If you want to ensure the user presses 'y' or 'Y' followed by the enter or return key, those two strings encode to "y\n" and "Y\n". You need to use fgets, for example:
char answer[2];
fgets(answer, sizeof answer, stdin);

if (strcmp(answer, "Y\n") == 0 || strcmp(answer, "N\n") == 0) {
/* ... */

Alternatively, you could use getchar to read a single character, since that's what it's meant for.

int answer = getchar(),
newline = getchar();

if (newline != '\n') {
/* Invalid input */
else if (answer == 'Y') {
/* Yes */
else if (answer == 'N') {
/* No */
else {
/* More invalid input */
0 Suraj Gautam · October 16, 2015
Gesu why you asking me such question :p
0 Mondher Ben Romdhane · October 19, 2015
try to remove the space before "    %c" in line 9 in scanf function
0 Suraj Gautam · October 19, 2015
LOL gesu try it
0 Suraj Gautam · October 28, 2015
don't be stupid dude. That code was only a small part.
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator