Solution for Exercise 7-18

ex0718

#include <stdio.h>

int main()
{
    char firstname[15];
    char lastname[15];

    printf("Type your first name: ");
    fgets(firstname,15,stdin);
    printf("Type your last name: ");
    fgets(lastname,15,stdin);
    printf("Pleased to meet you, %s %s.\n",firstname,lastname);
    return(0);
}

Notes

* This exercise demonstrates a flaw with using fgets() as a general-purpose text input function: The Enter key press (the newline) is read along with other characters, and stored as part of the string. For example, here's my sample run of the program:

Type your first name: Danny
Type your last name: Gookin
Pleased to meet you, Danny
 Gookin
.

* The Enter key press stored after my first name is displayed, bumping my last name to the following line. Then the period that ends the string is on a line by itself. You can correct this problem by reading in both strings at once, as shown in the following example:

ex0718 - both strings at once

#include <stdio.h>

int main()
{
    char name[30];

    printf("Type your first and last name: ");
    fgets(name,30,stdin);
    printf("Pleased to meet you, %s.\n",name);
    return(0);
}

* Alas, the output still retains the extra Enter character typed at the end of the string:

Type your first and last name: Danny Gookin
Pleased to meet you, Danny Gookin
.

* The period is still on a line by itself.

* Later examples in the book demonstrate how to strip out the \n in a string read by fgets().