Sams Teach Yourself C in 21 Days

(singke) #1
Manipulating Strings 511

17


10:
11: while (1)
12: {
13: puts(“\nEnter a line of text, a blank to exit.”);
14: gets(buf);
15:
16: if ( strlen(buf) == 0 )
17: break;
18:
19: for ( ctr = 0; ctr< strlen(buf); ctr++)
20: {
21: printf(“%c”, tolower(buf[ctr]));
22: }
23:
24: printf(“\n”);
25: for ( ctr = 0; ctr< strlen(buf); ctr++)
26: {
27: printf(“%c”, toupper(buf[ctr]));
28: }
29: printf(“\n”);
30: }
31: return 0;
32: }

Enter a line of text, a blank to exit.
My aun’t name is Carolyn C.
my aun’t name is carolyn c.
MY AUN’T NAME IS CAROLYN C.Enter a line of text, a blank to exit.
This listing prompts for a string on line 13 and uses gets()in line 14 to obtain
it. It then checks to ensure that the string isn’t blank (line 16). Because the
toupperandtolowermacros work with individual characters, this listing displays the
information in buf differently than the way Listing 17.14 did. You can see in line 19 that
a for loop is used to cycle through the characters. Each is then converted.

LISTING17.17 continued

INPUT/
OUTPUT

ANALYSIS

Where possible you should use the toupper()andtolower()macros rather
than the strupr()andstrlwr()non-ANSI functions. You can create your
own functions using toupper()andtolower(). Your functions would then
be ANSI compliant.

Note


28 448201x-CH17 8/13/02 11:13 AM Page 511

Free download pdf