The Yorn Function

When a computer program wants to know a Yes or No answer, the function I write is called yorn().

A yorn() function can be simple or complex. Simple functions limit the answer to one option, such as the (Y/n) prompts in Unix/Linux. This type of yorn() function interprets any key other than Shift+Y as “no” and the operation is canceled.

A complex yorn() function would accept as a positive response single keys Y or y and the full word Yes, YES, and all uppercase/lowercase combinations therein. It would similarly interpret a negative response and reject anything else as invalid, prompting for input again.

The difficulty with writing a complex yes-or-no function is compounded by stream input: The code doesn’t just read the Y or N, it must also contend with ES and O plus the Enter key press, all of which come squirting in through standard input. Upper and lower case letters must be considered. Overflow is an issue.

For this month’s Exercise, your task is to write a yorn() function. Here’s the skeleton you must work with:

#include <stdio.h>

int yorn(void)
{
}

int main()
{
    int r;

    while(1)
    {
        printf("Would you like to destroy the Earth?");
        r = yorn();
        if( r==1 )
        {
            puts("The Earth will be destroyed.");
            break;
        }
        if( r==2 )
        {
            puts("The Earth will be saved.");
            break;
        }
        puts("Invalid response");
    }

    return(0);
}

The yorn() function returns two valid integers: 1 for “Yes” and 2 for “No.” In my solution, zero references invalid input, but you can return any value other than 1 or 2 for invalid input.

Be aware that the question/prompt lies in an endless while loop. The code’s purpose is to extract a Yes or No response. The user need type only Y or N (or y or n), but they may also type Yes or No as valid responses. Your solution must deal with these situations and repeat the prompt when input is invalid. Anticipate the worst user to ensure that the code can handle horrible and improper input.

Click here to view my solution, but please try coding a bulletproof yorn() function on your own before you see what I’ve done.

2 thoughts on “The Yorn Function

  1. I hope you realize that by using the phrase “destroy the Earth” you have attracted the attention of the CIA, FBI, MI5, GCHQ, Mossad etc etc… 🙁

    I think I would probably use 0 for no/false and 1 for yes/true, or even stdbool.h. It might be worth expanding the spec of the yorn function to allow c(ancel) to provide a console equivalent of a Yes/No/Cancel message box.

  2. My solution could accommodate a third option, easily. See? This is why yorn() functions are so much fun! 😀

Leave a Reply