Programming in C

(Barry) #1
Variable-Length Character Strings 207

If s1,s2,and s3are defined to be character arrays of appropriate sizes, execution of
the statement


scanf ("%s%s%s", s1, s2, s3);


with the line of text


micro computer system


results in the assignment of the string "micro"to s1,"computer"to s2,and "system"
to s3. If the following line of text is typed instead:


system expansion


it results in the assignment of the string "system"to s1,and "expansion"to s2.
Because no further characters appear on the line, the scanffunction then waits for more
input to be entered from your terminal window.
In Program 10.5,scanfis used to read three character strings.


Program 10.5 Reading Strings with scanf


// Program to illustrate the %s scanf format characters


#include <stdio.h>


int main (void)
{
char s1[81], s2[81], s3[81];


printf ("Enter text:\n");

scanf ("%s%s%s", s1, s2, s3);

printf ("\ns1 = %s\ns2 = %s\ns3 = %s\n", s1, s2, s3);
return 0;
}


Program 10.5 Output


Enter text:
system expansion
bus


s1 = system
s2 = expansion
s3 = bus

Free download pdf