Home > Enterprise >  How should I do to be able to ask a yes or no question in C
How should I do to be able to ask a yes or no question in C

Time:09-12

I'm trying to make my code to... I guess recognize if I am pressing "y" or "n", and and do stuff depending on which one is in the input.

I thought it would be this simple, but unfortunately it isn't.

How am I supposed to do it?

#include <stdio.h>

int main(void)
 {
    char y;

    printf("Single provider (y/n)? ");
    scanf(" %c", &y);

    if (y == '121' || y == '89')
    {
        printf("single");
    }
    else
    {
        printf("not single");
    }
 }

CodePudding user response:

You are making a beautiful mix-up here: apparently have heard about ASCII codes and you want to apply them into your code. The idea is good, not the realisation:

Your code:

if (y == '121' || y == '89')

Correct code (without ASCII codes):

if (y == 'y' || y == 'Y')

Correct code (using ASCII codes):

if (y == 121 || y == 89) // ASCII_Code('Y')=89 and ASCII('y')=121

(Please don't remove the comment, it's very useful for readability)

Good luck

CodePudding user response:

int main(void)
 {
    int y;

    printf("Single provider (y/n)? ");
    do
    {
        y = fgetc(stdin);
    }while(y != EOF && y != 'y' && y != 'n');

    if(y != EOF)
        if (y == 'y')
        {
            printf("single");
        }
        else
        {
            printf("not single");  
        }
 }
  • Related