Sams Teach Yourself C in 21 Days

(singke) #1
Working with Characters and Strings 241

10


Thegets()Function
#include <stdio.h>
char *gets(char *str);
Thegets()function gets a string,str, from the standard input device, usually the key-
board. The string consists of any characters entered until a newline character is read. At
that point, a null is appended to the end of the string.
Then the gets()function returns a pointer to the string just read. If there is a problem
getting the string,gets()returns null.
Example
/* gets() example */
#include <stdio.h>
char line[256];
void main( void )
{
printf( “Enter a string:\n”);
gets( line );
printf( “\nYou entered the following string:\n” );
printf( “%s\n”, line );
}

Inputting Strings Using the scanf()Function ..............................................

You saw on Day 7 that the scanf()library function accepts numeric data input from the
keyboard. This function can also input strings. Remember that scanf()uses a format
stringthat tells it how to read the information entered. To read a string, include the speci-
fier%sinscanf()’s format string. Like gets(),scanf()is passed a pointer to the
string’s storage location.
How does scanf()decide where the string begins and ends? The beginning is the first
non-whitespace character encountered. The end can be specified in one of two ways. If
you use %sin the format string, the string runs up to (but not including) the next white-
space character (space, tab, or newline). If you use %ns(wherenis an integer constant
that specifies field width),scanf()accepts the next ncharacters or up to the next white-
space character, whichever comes first.
You can read in multiple strings with scanf()by including more than one %sin the for-
mat string. For each %sin the format string,scanf()uses the preceding rules to find the
requested number of strings in the input. For example
scanf(“%s%s%s”, s1, s2, s3);
If in response to this statement you enter January February March,Januaryis assigned
to the string s1,Februaryis assigned to s2, andMarchtos3.

,


S

YNTAX

,


17 448201x-CH10 8/13/02 11:17 AM Page 241

Free download pdf