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);
}
Output
Type your first name: Danny
Type your last name: Gookin
Please to meet you, Danny
Gookin
.
Notes
* Bonus points if you used a constant to set the buffer size as well as the second argument for the fgets() functions.
* 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, stored as part of the string, and output all ugly as shown above.
* It's also possible to code the solution for this Exercise to read 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);
}
* The output from the above code 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
.
* Later examples in the book demonstrate how to strip out the \n in a string read by fgets().
Copyright © 1997-2025 by QPBC.
All rights reserved
