Solution for Exercise 7-17

ex0717

#include <stdio.h>

int main()
{
    const int size = 3;
    char name[size];

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

Output

Who are you? Dennis
Glad to meet you, De.

Notes

* The purpose of this program was to show how the 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 size to 30 or 40 or whatever. This change needs to be made only once, not in the other locations where the string size is referenced.