The following functions are used for string input and output
printf() with format specifier %s
scanf() with format specifier %s
gets()
puts()
We have seen the use of printf and scanf for accepting and displaying integer, character etc. data types. These two functions can be with string using the format specifier %s.
Apart from these functions, there are two special functions for accepting and displaying strings they are gets() and puts().
The difference between scanf and gets function is that gets does not require format specifier and scanf does not allow a string with spaces. gets() allows a strings to contain spaces.
String Input
Use %s field specification in scanf to read string ignore leading white space
reads characters until next white space encountered C stores null (\0) char after last non-white space char Reads into array (no ‘&’ before ‘Name’, array is a pointer) Example:
char Name[10];
scanf(“%s”, Name);
Same example can be written using gets() char Name[10];
gets(Name)
String Input (cont)
Can use the width value in the field specification to limit the number of characters read
char Name[11];
scanf(“%10s”,Name);
Remember, you need one space for the ‘\0’ width should be one less than size of array
Strings shorter than the field specification are read normally, but C always stops after reading 10 characters.
String Output
Use %s field specification in printf: characters in string printed until ‘\0’ encountered char Name[10] = “Rich”;
printf(“%s”, Name); /* outputs Rich */
Same example can be written using puts() char Name[10]=“Rich”;
puts(Name)
Can use width value to print string in space: printf(“|%10s|”, Name); /* outputs | Rich| */ Use ‘-’ flag to left justify:
printf(“|%-10s|”, Name); /* outputs |Rich | */
Comments
Post a Comment
Please give us feedback through comments