Explain the standard 1/0 functions for reading and writing stings.
Answers
Reading and Writing String
Reading Strings
Format conversion ”%s” can be used in scanf for reading strings not
containing white spaces: scanf("%s", str)
’&’ not required before str as it is a pointer.
C string library provides gets(str) to read a string.
It does not skip white spaces like scanf does.
But, scanf and gets have no way to know the size of the array in
advance.
So potentially, they could attempt to store character past the array.
scanf can use "%.ns" conversion to avoid this problem.
But gets is dangerous.
R. K. Ghosh (IIT-Kanpur) C Programming April 6, 2011 2 / 4
C Programming
Strings
Reading and writing strings
Reading and Writing String
Reading Character by Character
Since both scanf and gets are potentially risky, character by
character reading using getchar, and similarly writing using putchar
are safer to use.
Code for readline for example will be:
i n t r e a d L i n e ( c h a r s t r [ ] , i n t n ) {
i n t ch , i = 0 ;
w h i l e ( ( ch = g e t c h a r ( ) ) != ’ \n ’ ) {
i f ( i < n )
s t r [ i ++] = ch ;
}
s t r [ i ] = ’ \0 ’ ;
r e t u r n i ;
}
R. K. Ghosh (IIT-Kanpur) C Programming April 6, 2011 2 / 4
C Programming
Strings
Reading and writing strings
Reading and Writing String
Accessing Characters in a String
i n t c o u n tW hi teS p ace ( c o n s t s [ ] ) {
i n t c n t = 0 , i ;
f o r ( i = 0 ; s [ i ] != ’ \0 ’ ; i ++) {
i f ( s [ i ] = ’ ’ )
c n t++;
r e t u r n c n t ;
}
i n t c o u n tW hi t e S p a c e s ( c o n s t c h a r ∗ s ) {
f o r ( ; ∗ s != ’ \0 ’ , s++)
i f (∗ s == ’ ’ )
c n t++;
r e t u r n c n t ;
}
R. K. Ghosh (IIT
"The standard I/O functions for reading strings in the programming language C are gets() and scanf().
The scanf() function is more of an all-purpose function than being a function to be used for reading strings especially.
The major drawback of the scanf() function is that it reads a string value only up to the occurrence of the next whitespace (i.e. it only reads a single word). Whereas, the gets() function is a standard input function which is more suitable choice for string input as it overcomes the drawback of any function.
The standard functions for output of strings are printf() and puts(). The puts() function can be used for the output of strings only whereas the printf() function can be used to output any type of data."