20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Variable-Length Character Str<strong>in</strong>gs<br />

207<br />

If s1, s2,and s3 are def<strong>in</strong>ed to be character arrays of appropriate sizes, execution of<br />

the statement<br />

scanf ("%s%s%s", s1, s2, s3);<br />

with the l<strong>in</strong>e of text<br />

micro computer system<br />

results <strong>in</strong> the assignment of the str<strong>in</strong>g "micro" to s1, "computer" to s2,and "system"<br />

to s3. If the follow<strong>in</strong>g l<strong>in</strong>e of text is typed <strong>in</strong>stead:<br />

system expansion<br />

it results <strong>in</strong> the assignment of the str<strong>in</strong>g "system" to s1,and "expansion" to s2.<br />

Because no further characters appear on the l<strong>in</strong>e, the scanf function then waits for more<br />

<strong>in</strong>put to be entered from your term<strong>in</strong>al w<strong>in</strong>dow.<br />

In Program 10.5, scanf is used to read three character str<strong>in</strong>gs.<br />

Program 10.5<br />

Read<strong>in</strong>g Str<strong>in</strong>gs with scanf<br />

// Program to illustrate the %s scanf format characters<br />

#<strong>in</strong>clude <br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

char s1[81], s2[81], s3[81];<br />

pr<strong>in</strong>tf ("Enter text:\n");<br />

scanf ("%s%s%s", s1, s2, s3);<br />

}<br />

pr<strong>in</strong>tf ("\ns1 = %s\ns2 = %s\ns3 = %s\n", s1, s2, s3);<br />

return 0;<br />

Program 10.5 Output<br />

Enter text:<br />

system expansion<br />

bus<br />

s1 = system<br />

s2 = expansion<br />

s3 = bus

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!