C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

The puts() and gets() functions provide an easy way to print and get strings. Their descriptions
are in stdio.h, so you don’t have to add another header file for puts() and gets(). puts()
sends a string to the screen, and gets() gets a string from the keyboard. The following program
demonstrates gets() and puts(). As you look through it, notice that neither printf() nor
scanf() is required to input and print strings.


Click here to view code image


// Example program #2 from Chapter 19 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter19ex2.c
/* This program asks a user for their hometown and the two-letter
abbreviation of their home state. It then uses string concatenation
to build a new string with both town and state and prints it using
puts. */
// stdio.h is needed for puts() and gets()
// string.h is needed for strcat()
#include <stdio.h>
main()
{
char city[15];
// 2 chars for the state abbrev. and one for the null zero
char st[3];
char fullLocation[18] = "";
puts("What town do you live in? ");
gets(city);
puts("What state do you live in? (2-letter abbreviation)");
gets(st);
/* Concatenates the strings */
strcat(fullLocation, city);
strcat(fullLocation, ", "); //Adds a comma and space between
// the city
strcat(fullLocation, st); //and the state abbreviation
puts("\nYou live in ");
puts(fullLocation);
return(0);
}

Tip

strcat() has to be used three times: once to add the city, once for the comma, and
once to tack the state onto the end of the city.
Free download pdf