When You Need a Function – Solution

For my solution to this month’s Exercise, I crafted the ask() function. That’s because the original code prompts three times with a question string and an answer buffer, which is the repetitive part of the program I chose to cast into a function.

Here is my ask() function:

void ask(char *question, char *answer, int length)
{
    char *a;

    printf("%s",question);
    fgets(answer,length,stdin);

    /* remove newline from input */
    a = answer;
    while(*a != '\n')
        a++;
    *a = '\0';      /* replace newline with null character */
}

The function takes two strings as arguments: question and answer, plus a length variable.

The question string is displayed. Then the fgets() function reads the input and stores it at the answer string’s location in memory. The length variable gauges input size.

Because fgets() stores the newline at the end of input, a while loop is added to replace the newline ('\n') with a null character ('\0').

Nothing needs to be returned from the function because answer is a pointer. Therefore the function is a void type.

Here is the full code for my solution:

#include <stdio.h>

void ask(char *question, char *answer, int length)
{
    char *a;

    printf("%s",question);
    fgets(answer,length,stdin);

    /* remove newline from input */
    a = answer;
    while(*a != '\n')
        a++;
    *a = '\0';      /* replace newline with null character */
}

int main()
{
    char name[32], color[16], quest[64];

    ask("What is your name? ",name,32);
    ask("What is your favorite color? ",color,16);
    ask("What is your quest? ",quest,64);

    printf("%s, whose favorite color is %s, ",
            name,
            color);
    printf("you shall succeed!\n");

    return(0);
}

As always, your solution may vary. In fact, as I stated in the original post, this code is brief, so creating a function isn’t truly necessary. My point is to look for repetition in your code and craft functions that eliminate repetition but also help document what the program is doing.

Leave a Reply