Read a Whole Line in C Using Fgets and Sscanf
Introduction
The scanf() office is a widely used role in C/C++. Although the syntax to employ information technology is simple, it is of import to understand some areas where its usage would require careful handling. I such area is when fgets() is used later scanf().
In this article, nosotros will address this problem of how fgets() doesn't piece of work later on scanf() and also derive the solutions to information technology. Before that let'south empathise how the scanf() and fgets() functions work.
The scanf() office in C/C++
The scanf() is a function in the C library that reads formatted data from the standard input stream so writes the output into the given arguments. This function is declared every bit follows:
int scanf( const char *format, ... ); Let'southward discuss the various aspects of this declaration.
- int refers to the type of render value of the part.
- format is the C cord that contains the type specifiers. Type specifiers are used to define the blazon of data that will be stored in a variable which is taken as input using the scanf() function. The following table displays a few examples of the type specifiers identified by scanf().
| Format Specifiers | Blazon of Data |
| %c | Grapheme |
| %d | Signed integer |
| %f | Floating point |
| %x | Unsigned integer in hexadecimal format |
| %s | String |
- The ellipsis ("…") points to the fact that the scanf() function may comprise a variable number of arguments, given that every argument is a memory address into which the converted consequence is written into.
The scanf() function is part of a family unit of functions that substantially accept the same purpose but read the input from other sources. For instance, fscanf() reads from the file stream and sscanf() reads from a nil-terminated string buffer.
Hither is a pocket-size example of how nosotros utilize the scanf() function:
int main () { char str1[20]; printf("Enter proper name: "); scanf("%due south", str1); printf("Entered Name: %s\northward", str1); return(0); } Input:
Enter name: Ninja
Output:
Entered name: Ninja
The fgets() function in C/C++
The fgets in the fgets() office stands for 'file get string'. This is essentially a function that is used to read upward to due north characters from the stream (file stream or standard input stream) into string str. It is alleged as:
char* fgets(char* str, int northward, FILE* stream);
Allow's discuss every aspect of this declaration.
- int n refers to the number of characters that need to be read into the string.
- FILE* stream is the pointer to the file stream from which the input is being read. This is replaced by stdin when reading from the standard input.
- The pointer to str is the return value of this office.
Let's take an example to sympathise how fgets() reads from a file.
# include <stdio.h> int master( ) { FILE *file ; char str1[forty] ; printf( "The file sample.txt is opened in read style" ) ; file = fopen( "sample.txt", "r" ) ; if ( file == Cipher ) { printf( "sample.txt couldn't be opened" ) ; return 0; } printf( "sample.txt is being read." ) ; while( fgets ( str1, 40, file) != Zilch ) printf( "%s" , str1 ) ; printf("The file sample.txt is now airtight") ; fclose(file) ; return 0; } Output:
Opening the file test.c in read mode
Reading the file exam.c
Welcome to Coding Ninjas
Closing the file test.c
The fgets() function terminates its functioning if 1 of the following atmospheric condition is fulfilled. These conditions will be important to continue in mind during our discussion on why fgets() doesn't piece of work after scanf().
- A newline character is encountered
- The office has read n – 1 character
- EOF (End of File) has been reached
Problem with using fgets() after scanf()
Now that we know how the fgets() and scanf() functions work, let'southward expect at what happens if nosotros use the fgets() function right after the scanf()function and whether fgets() doesn't work after scanf().
int main(){ int x; char str[50]; scanf("%d", &ten); fgets(str, 50, stdin); printf("x = %d, str = %s", x, str); return 0; } Input:
5
Ninja
Output:
ten = v, str =
We tin see here that the string "Ninja" is non printed. What is the reason behind this? The problem is because of a certain characteristic of the scanf() office.
When scanf() reads input from the standard input stream, it also creates a newline graphic symbol in the buffer. And then in the above code, after reading the integer x, the scanf() function left a newline character. The fgets() function so reads this newline character and terminates the functioning (recall the three atmospheric condition that we discussed for the fgets() operation to stop reading input). Therefore the string "Ninjas" is ignored past the fgets() office and does not get printed.
This feature of scanf() is something that is important to note whenever we employ this office. But now the question is, is at that place a solution to this problem of how fgets() doesn't piece of work after scanf()? How do you print the string "Ninjas" likewise?
The solution to the problem
After assessing the trouble of why fgets() doesn't work after scanf(), it is time to derive a solution. Find the code below.
int main(){ int x; char str[fifty]; scanf("%d\due north", &x); fgets(str, 50, stdin); printf("x = %d, str = %s", 10, str); return 0; } Input:
10
Ninjas
Output:
x = x, str = Ninjas
Practise you see the difference? We have introduced an extra "\due north" in scanf("%d\n", &x). By doing this, nosotros brand scanf() read a new line. We can also achieve this by
- Introducing an actress space equally in scanf("%d ", &x).
- Calculation a getchar() part afterwards the scanf() function to read an extra newline.
Therefore, the fgets() volition not have to read the newline and will read the string input. Thus solving the problem of how fgets() doesn't work after scanf().
Frequently Asked Questions
How do I make Fgets work after scanf?
This tin can exist solved past introducing a "\north" in scanf() every bit in scanf("%d\n", &x) or past adding getchar() after scanf().
Why fgets doesn't work afterward scanf?
This tin be solved past introducing a "\n" in scanf() as in scanf("%d\n", &x) or by adding getchar() after scanf(). The fgets() function and so read this newline character and terminated operation.
Is Fgets better than Scanf?
There are certain aspects to look at before deciding so. fgets() can read from any file stream but scanf() but reads from standard input.
What is the syntax for using scanf()?
Hither is the syntax for using scanf(),
int scanf( const char *format, … );
What is the syntax for using fgets()?
Here is the syntax for using fgets(),
char* fgets(char* str, int n, FILE* stream);
What does Scanf render in C?
Scanf returns the total number of inputs successful or EoF(Finish of Line) if at that place is an error.
Key Takeaways
While using the scanf() function, a very common problem is faced if it is used before an fgets() part. Because of this issue, the fgets() function does not read some office of the input as the scanf() part leaves a newline graphic symbol in the buffer. This tin can be solved by introducing a "\n" in scanf() as in scanf("%d\due north", &x) or past adding getchar() afterward scanf().
By Khushi Sharma
Source: https://www.codingninjas.com/blog/2021/07/27/solved-the-problem-with-using-fgets-after-scanf/
0 Response to "Read a Whole Line in C Using Fgets and Sscanf"
Post a Comment