Solution for Exercise 7-17

ex0717

#include <stdio.h>

#define INPUT_SIZE 3

int main()
{
    char name[INPUT_SIZE];

    printf("Who are you? ");
    fgets(name,INPUT_SIZE,stdin);
    printf("Glad to meet you, %s.\n",name);
    return(0);
}

Notes

* The purpose of this program was to show how the INPUT_SIZE constant restricts input to only two characters, plus the \0 — the null character that terminates all strings in C. It's easier to see that only two characters are read in the output.

* By setting a constant, it's now easier to adjust the input size. So if you really want the program to work, you can change the value of INPUT_SIZE to 30 or 40 or whatever.

* Because the fgets() function captures the newline (Enter key press), the final line of output is split between two lines. Refer to Exercise 7-16.