Sams Teach Yourself C in 21 Days

(singke) #1
LISTING10.5 get.c. Using gets()to input string data from the keyboard
1: /* Demonstrates using the gets() library function. */
2:
3: #include <stdio.h>
4:
5: /* Allocate a character array to hold input. */
6:
7: char input[81];
8:
9: int main( void )
10: {
11: puts(“Enter some text, then press Enter: “);
12: gets(input);
13: printf(“You entered: %s\n”, input);
14:
15: return 0;
16: }

Enter some text, then press Enter:
This is a test
You entered: This is a test
In this example, the argument to gets()is the expression input, which is the
name of a type chararray and therefore a pointer to the first array element. The
array is declared with 257 elements in line 7. Because the maximum line length possible
on most computer screens is 256 characters, this array size provides space for the longest
possible input line (plus the null character that gets()adds at the end).
Thegets()function has a return value, which was ignored in the previous example.
gets()returns a pointer to type charwith the address where the input string is stored.
Yes, this is the same value that is passed to gets(), but having the value returned to the
program in this way lets your program test for a blank line. Listing 10.6 shows how to do
this.

LISTING10.6 getback.c. Using the gets()return value to test for input of a blank line
1: /* Demonstrates using the gets() return value. */
2:
3: #include <stdio.h>
4:
5: /* Declare a character array to hold input, and a pointer. */
6:
7: char input[257], *ptr;
8:
9: int main( void )
10: {

238 Day 10

INPUT/
OUTPUT

ANALYSIS

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

Free download pdf