Reading Strings From the Terminal


Reading Strings From the Terminal


Reading Strings From the Terminal
The familiar input function scanf can be used with %s format specification to read in a string of characters.
        char address[15];
        scanf("%s", address);
   The problem with the scanf function is that it terminates its input on the first white space it finds.Therefore if the following line of text is typed in at the terminal,NEW YORK
then only the string "NEW" will be read into the array address,since the blank space after the word "NEW" will terminate the string.

Note: Unlike previous scanf calls, in the case of character arrays , the ampersand(&) is not required
before the variable name. The scanf function automatically terminates the string that is read with a null character and therefore the character array should be large enough to hold the input string plus the null character.'C' does not provide operators that work on strings directly. For instance we cannot assign one string to another directly.
      string = "ABC";
      string1 = string2;   are not valid.

Writing strings to screen:
 The %s format can be used to display an array of characters that is terminated by the null character.% 10.4s indicates that the first four characters are to be printed in a field width of 10 columns.%-10.4s indicates that the string will be printed left justified.

Note :
1.When the field width is less than the length of the string, the entire string is printed.
2.The integer value on the right side of the decimal print  specifies the number of characters to be printed.
3.When the number of characters to be printed is specified as  'zero' nothing is printed.
4.The minus sign in the specification causes the string to be   printed left justified

No comments:

Post a Comment