We can read a string using the %s conversion specification in the scanf function. However, it has a limitation that the strings entered cannot contain spaces and tabs. To overcome this problem, the C standard library provides the gets function. It allows us to read a line of characters (including spaces and tabs) until the newline character is entered, i. e., the Enter key is pressed. A call to this function takes the following form:
where s is an array of char, i. e., a character string. The function reads characters entered from the keyboard until newline is entered and stores them in the argument string s, The newline character is read and converted to a null character (\O) before it is stored in s. The value returned by this function, which is a pointer to the argument string s, can be ignored. The C standard library provides another function named puts to print a string on the display. A typical call to this function takes the following form:
where s is an array of char, i. e., a character string. This string is printed on the display followed by a newline character.
Example: String I/O using the gets and puts function
Consider the code segment given below.
puts("Enter a line of text:\n");
A line of text typically contains 80 characters. Thus, the array str has been declared to store 81 characters with a provision to store the null terminator. The output of this code segment is shown below.
Enter a line of text:
Programming in C language is fun'
Programming in C language is fun!