-2

i am trying to learn c and i want to make a yesno with a single char. here is my code:

i have tried this

#include <stdio.h>
#include <stdlib.h>

//just playing

int main()
{
    char yesno;
    printf("TEST [Y/n] ");
    scanf(" %c", &yesno);
    if(yesno == "y") {
        printf("You did yes!!");
    } else if(yesno == "n") {
        printf("You did no!");
    } else {
        printf("Not valid!!!");
    }
    return 0;
}

and it skips to else automatically why is this

update: i did not know that this is a duplicate. idk what double quotes were and singles were before

lebro111
  • 11
  • 1

2 Answers2

4

Here

yesno == "y"

you are comparing a char yesno with string "y". It should be

yesno == 'y'  /* use single quotation instead of double quotation */

Side note always compile your code with minimum below flags & don't ignore the warnings, work on those. For e.g

gcc -Wall -Wstrict-prototypes -Wpedantic -Werror test.c

where Werror converts warning into error & stops the compilation so that you shouldn't jump to the output & forces you to read & solve the compiler error message.

Achal
  • 11,821
  • 2
  • 15
  • 37
1

Lesson learned : Never ever ignore compiler warnings.

use 'y' instead of "y"

This will work :) Happy learnings

#include <stdio.h>
#include <stdlib.h>

//just playing

int main()
{
    char yesno;
    printf("TEST [Y/n] ");
    scanf(" %c", &yesno);
    if(yesno == 'y') {
        printf("You did yes!!");
    } else if(yesno == 'n') {
        printf("You did no!");
    } else {
        printf("Not valid!!!");
    }
    return 0;
}
zappy
  • 1,864
  • 3
  • 18
  • 36