Strings Input and Output functions in C
Overview
In C programming, taking input means getting information from the user and storing it as a string, while giving output involves providing information to the user in a string format. To get a string input in C without spaces, we often use the scanf() function with the %s specifier. When dealing with string input that may have spaces, we have different methods like gets(), fgets(), and scansets within scanf(). Let's discuss this in detail.
What is the Input and Output of a String in C?
Taking string input in C means asking the user to provide some information for the program to manipulate and analyse and storing this information in the form of a string. Similarly, giving output as string means printing into the console some information which the programmer wants the user to know in the form of strings. It is necessary to use strings as input and output strings to the user in C as shown in the example above.
While taking string input in C, we basically have two scenarios: strings that have spaces and strings without spaces. In the next sections, we will look at both these cases and the functions that can be used for the same.
How to Take Input of a String in C Without Spaces?
In C, we can use scanf() to take a string input in C without spaces. Like other data types, we have an access specifier (also known as format specifier) to take input as a string in C as well. The access specifier for string is %s.
The syntax for using scanf()function in C :
Here, s is the pointer which points to the array of characters where the input taken as a string will be stored.
Note that in the syntax, we don't use the & symbol with s. This is because & is used to access the address of the variable, but as C doesn't have a string data type, s already stores the address of the character array where the string is stored.
Let us look at an example to understand the working of scanf() in C.
Output
Advantages and Disadvantages of using scanf()
The scanf() function is probably the easiest way to string input in C. We just need the access specifier %s and the pointer to the variable where we want the string to be stored, and it becomes very easy to input the string in C.
On the other hand, there is no limitation on the size of the string that can be taken as an input by scanf() by default. This may cause overflow if we don't have the required space. But this can be easily fixed by specifying an explicit upper bound of memory which can prevent overflow. Apart from this, there is a chance of a failed input which would lead to our variable pointer pointing to an unknown location, which can lead to further problems in the code.
Hence, the scanf() function should be preferred when we know the string we want to input doesn't contain white spaces and that it will not exceed the memory buffer.
We will explore the output of strings without space in C in the later sections of the article. Let us first see how to take input for string in C with spaces.
How to Take Input of a String With Spaces in C?
In C, there is a problem with simply taking the string as input using access specifier %s. If we take any string as input in C which has a whitespace, i.e., space, tab or newline character in it, then only the part before the whitespace would be taken as the input. Let's take a look at an example to understand this issue better.
Output
Even though we entered This is my sentence, the char array sentence only stored This and the remaining part was discarded because the %s access specifier works in a way that it reads the sequence of characters until it encounters whitespace (space, newline, tab, etc). Thus, as the first space is encountered just after the word This the char array sentence stores only the string This. Hence, it is impossible to take input of a string with spaces by just using the %s access specifier in scanf() function. Then how do we take such strings as an input in C?
Let's take a look at some methods which we can use to take a string input in C with spaces.
Methods to Accept String With Space in C
We'll look at four different methods to take a string input in C with spaces(whitespaces).
-
gets()
This is a C standard library function. gets() takes a complete line as input and stores it in the string provided as a parameter. The working of gets() is such that it keeps reading the input stream until it encounters a newline character: \n. Hence, even if the string input in C has spaces in it, all of them get included as input until \n doesn't occur.
The syntax for gets() in C is:
Here, s is the pointer which points to the array of characters where the input taken as a string will be stored and returned. This function will return the string in s when it finishes successfully.
Let us look at the previous example, but with using the gets() function to understand more clearly.
Output
This time the code gave the complete string, I am happy today as output, including the spaces. This is because we used the gets() method.
So far, gets() seems to be a great method to take string input in C with spaces. But gets() doesn't care about the size of the character array passed to it. This means, in the above example, if the user input would be more than 30 characters long, the gets() function would still try to store it in the sentence[] array, but as there is not much available space, this would lead to buffer overflow. Because of this limitation, using the gets() function is not preferable. We will explore other methods in the upcoming sections.
Note: The gets() method is no longer a standard function according to the C11 standard ISO/IEC 9899:2011. But it is still available in libraries and will continue to be available for compatibility reasons.
-
fgets()
To overcome the above-listed limitation, we can use fgets() function. The fgets() function is similar to gets(), but we can also specify a maximum size for the string which will be taken as a string input in C from the user. This means that it reads either the complete line as a string and stores it in the array if the size is less than what is specified as a parameter (say: sz), else it reads only sz characters provided by the user so that no buffer overflow occurs.
The syntax for fgets() in C is:
Here, s is the pointer which points to the array of characters where the input taken as a string will be stored and returned. The sz variable specifies the maximum allowed size for the user input and stream is used to denote the stream from which the input is to be taken (usually stdin, but it can also be a file).
Let us look at an example to understand more clearly.
Output
Only 20 characters of the input were stored in the char array, 'sentence' as 20 was specified as the maximum size in fgets() and hence buffer overflow was avoided.
Comparision between gets() and fgets()
Although gets() and fgets() are similar in the sense that they both take a complete line as input, but they also have many dissimilarities.
While gets() can take string input in C only from the standard input stream, fgets() can take string input in C from both the standard input stream or from some file. Also, while the gets() method converts the \n character to \0 to make it a null-terminated string, the fgets() method does not do so. Instead, it adds a \0 symbol after the \n character to achieve the same.
Using scanset %[ ] in scanf()
Scanset is denoted by %[]. It can be used inside the scanf() function, and we can enclose individual characters or a range of characters within the scanset expression. Using this scanf() will only process these characters which have been specified inside the square brackets. We can also include multiple characters by adding commas in between the characters.
There are two ways by which we can use scanset to take input of a string in C with spaces.
-
{%[^\n]%*c} inside scanf
We can use the expression {%[^\n]%*c} inside scanf() to take the complete line including spaces as a string input in C.
Let us look at this expression in detail. In this case, we have ^\n inside the scanset brackets. The circumflex symbol ^ is used in this case. The use of this symbol is that it directs the specifier to stop reading once the character specified after it occurs once in the input. In this case, we have the \n newline character. Hence all the characters are taken as input until a new line occurs. As the newline character will also be taken as input, we discard it by further including %*c, so that only the user input is stored in the string.
The complete syntax for this method is:
Here, s is the pointer which points to the array of characters where the input taken as a string will be stored.
Let us look at an example to understand more clearly.
Output
-
%[^\n]s inside scanf
We can also use the expression %[^\n]s inside scanf() to take the complete line including spaces as a string input in C.
Let us look at this expression in detail. The characters [] denote the scanset character. In this case, we have ^\n inside the brackets, the circumflex symbol at the start will make sure all the characters are taken as input until the newline character \n is encountered. The expression [^\n] is included between the % and the s characters as %s is used as an access specifier for taking strings as input in C.
The complete syntax for this method is:
Here, s is the pointer which points to the array of characters where the input taken as a string in C will be stored.
Let us look at an example to understand more clearly.
Output
In the next sections, we will take a look at how we can string output in C.
How to Output a String Without Spaces in C?
-
using printf()
If we want to do a string output in C stored in memory and we want to output it as it is, then we can use the printf() function. This function, like scanf() uses the access specifier %s to output strings.
The complete syntax for this method is:
Here, s is the pointer which points to the array of characters which contains the string which we need to output.
Let us look at an example to understand the printf() function in C.
Output
This was the case when there was only one string and we had to output it as it is. But, if we want to print two strings and don't want space in between, we can use the fputs() function.
-
using fputs()
The fputs() function can be used to output two strings in C without space in between as it does not transfer the control to a new line so that even if another string is printed after it, both of them will be on the same line.
The complete syntax for this method is:
Here, s is the pointer which points to the array of characters which contains the string which we need to output.
Let us look at an example to understand this better.
Output
Both the strings have been printed in the same line, without any space as we used the fputs() function, which doesn't transfer the control to the next line.
How to Output a String With Spaces in C?
We saw how we can output a string in C without spaces, but what if we want to output a string in C with spaces? We can use the following two methods:
-
using printf() with \n
We saw the printf() function which we used to output a string in C as it is to the user. But, if we wanted to output two strings with a space in between them or conversely output two strings in different lines, we could do this also by using the printf() function.
To output two strings in two separate lines in C, we will have to include the newline character \n in the printf() function. The newline character will make sure that the next time anything is printed, it is printed in the next line. The complete syntax for this method is:
Here, s and s1 are the pointers which point to the array of characters which contain the strings that we need to output. Because of the \n newline character, s1 string will be output to the user in the next line.
To output two strings with a space in between, but in the same line, we just need to include that space in the printf() function. The complete syntax for this method is:
Here, s and s1 are the pointers which point to the array of characters which contain the strings that we need to output.
Let us look at an example to understand this better.
Output
-
using puts()
Another function which we can use to output a string in C is the puts() function.
The thing to note however is that after printing the given string in the output, the puts() function transfers the control to the next line. So any other string that we print after the execution of the puts()line will be printed in the next line by default and not in the same line.
The complete syntax for this method is:
Here, strptr is the pointer which points to the array of characters which contains the string which we need to output.
Let us look at an example to understand this better.
Output
As you can see in the code, we never specified that we need to leave a line after printing the first name, but the code still did, because of using the puts() function, which by default transfers control to the next line after printing.
Comparision between puts() and fputs()
The puts() and fputs() functions both are used to output strings to the user. Let us also look at the differences in their working.
While the puts() method converts the null termination character \0 to the newline character \n, the fgets() method does not do so. Hence, in the case of puts(), the control is transferred to a new line in the output, but in case of fputs(), it remains in the same line.
Examples
Let us look at some examples to revise the methods described above.
Example 1:
Program that takes student's name (with spaces) and city (without spaces) as input and prints them.
Output
In the above code, the complete name of a person may have spaces, hence we take it as input by using gets() and output it using prinf() with \n, whereas the city name won't have any spaces, and so we take it as input using scanf() and output it using fputs().
Example 2:
Saving a security question and answer for a user
Output
This code uses scanf(), printf() and gets() functions to take string input in C and string output in C with and without spaces.
Conclusion
- Taking string input in C means storing information given by the user in the form of a string. Giving string output in C means providing information to user in the form of a string.
- The function scanf() with the access specifier %s can be used to take a string input in C without spaces.
- To take a string input in C with spaces, the following methods are used:
- gets()
- fgets()
- {%[^\n]%*c} inside scanf()
- %[^\n]s inside scanf()
- To output a string without spaces in C, the following methods are used:
- printf() along with the access specifier %s.
- fputs()
- To output a string with spaces in C, the following methods are used:
- printf() with \n
- puts()