Using Fgets to Not Read New Line

Introduction

The scanf() function is a widely used function in C/C++. Although the syntax to use information technology is simple, information technology is of import to empathize some areas where its usage would require careful handling. One such area is when fgets() is used after scanf().

In this article, we will accost this problem of how fgets() doesn't work subsequently scanf() and too derive the solutions to information technology. Before that let'southward sympathise how the scanf() and fgets() functions piece of work.

The scanf() function in C/C++

The scanf() is a function in the C library that reads formatted data from the standard input stream and and so writes the output into the given arguments. This function is alleged as follows:


          int scanf( const char *format, ... );        

Let'south discuss the various aspects of this declaration.

  1. int refers to the type of return value of the function.
  1. format is the C string that contains the type specifiers. Blazon specifiers are used to define the blazon of information that will exist stored in a variable which is taken as input using the scanf() function. The following tabular array displays a few examples of the type specifiers identified by scanf().
Format Specifiers Type of Information
%c Graphic symbol
%d Signed integer
%f Floating point
%x Unsigned integer in hexadecimal format
%southward String
  1. The ellipsis ("…") points to the fact that the scanf() function may incorporate a variable number of arguments, given that every statement is a memory address into which the converted result is written into.

The scanf() office is part of a family of functions that substantially have the same purpose but read the input from other sources. For example, fscanf() reads from the file stream and sscanf() reads from a zero-terminated string buffer.

Here is a pocket-sized instance of how we apply the scanf() role:

          int main () {    char str1[20];     printf("Enter name: ");    scanf("%s", str1);     printf("Entered Name: %s\northward", str1);        return(0); }                  

Input:

Enter proper noun: Ninja

Output:

Entered proper name: Ninja

The fgets() office in C/C++

The fgets in the fgets() function stands for 'file get cord'. This is essentially a role that is used to read up to north characters from the stream (file stream or standard input stream) into cord str. It is declared equally:

char* fgets(char* str, int north, FILE* stream);

blog banner 1

Let'south discuss every attribute of this proclamation.

  • int due north refers to the number of characters that need to exist read into the string.
  • FILE* stream is the pointer to the file stream from which the input is beingness read. This is replaced by stdin when reading from the standard input.
  • The arrow to str is the return value of this function.

Let's take an example to sympathise how fgets() reads from a file.

          # include <stdio.h> int main( ) {          FILE *file ;          char str1[forty] ;          printf( "The file sample.txt is opened in read way" ) ;          file = fopen( "sample.txt", "r" ) ;          if ( file == Nothing )          {                  printf( "sample.txt couldn't exist opened" ) ;                  return 0;          }          printf( "sample.txt is beingness read." ) ;          while( fgets ( str1, 40, file) != NULL )          printf( "%southward" , str1 ) ;          printf("The file sample.txt is now closed") ;          fclose(file) ;          return 0; }                  

Output:

Opening the file test.c in read way
Reading the file examination.c
Welcome to Coding Ninjas
Closing the file test.c

The fgets() role terminates its operation if one of the following weather is fulfilled. These conditions will be important to keep in listen during our word on why fgets() doesn't work after scanf().

  • A newline grapheme is encountered
  • The part has read n – i grapheme
  • EOF (Terminate of File) has been reached

Problem with using fgets() later scanf()

At present that nosotros know how the fgets() and scanf() functions piece of work, let's expect at what happens if we use the fgets() function correct after the scanf()function and whether fgets() doesn't work after scanf().

          int principal(){  	int 10; 	char str[50]; 	scanf("%d", &x); 	fgets(str, 50, stdin); 	printf("x = %d, str = %south", 10, str); 	return 0;  }        

Input:

5
Ninja

Output:

x = 5, str =

We tin can see here that the string "Ninja" is not printed. What is the reason behind this? The problem is considering of a sure feature of the scanf() function.

When scanf() reads input from the standard input stream, it also creates a newline character in the buffer. So in the above code, after reading the integer x, the scanf() function left a newline character. The fgets() function then reads this newline graphic symbol and terminates the performance (recall the 3 conditions that nosotros discussed for the fgets() operation to stop reading input). Therefore the string "Ninjas" is ignored by the fgets() role and does not get printed.

This feature of scanf() is something that is important to notation whenever nosotros use this function. But now the question is, is there a solution to this problem of how fgets() doesn't work after scanf()? How practise you print the string "Ninjas" as well?

The solution to the problem

After assessing the problem of why fgets() doesn't work after scanf(), it is time to derive a solution. Notice the code below.

          int primary(){  int x; char str[50]; scanf("%d\due north", &10); fgets(str, fifty, stdin); printf("x = %d, str = %s", x, str); return 0; }        

Input:

10
Ninjas

Output:

x = 10, str = Ninjas

Do yous see the difference? Nosotros have introduced an extra "\n" in scanf("%d\n", &x). Past doing this, we make scanf() read a new line. Nosotros can also accomplish this by

  • Introducing an actress space as in scanf("%d ", &x).
  • Calculation a getchar() function after the scanf() function to read an actress newline.

Therefore, the fgets() will non have to read the newline and will read the cord input. Thus solving the problem of how fgets() doesn't piece of work later on scanf().

Frequently Asked Questions

How do I make Fgets work after scanf?

This can exist solved by introducing a "\due north" in scanf() as in scanf("%d\n", &x) or past adding getchar() later on scanf().

Why fgets doesn't work after scanf?

This can be solved past introducing a "\north" in scanf() as in scanf("%d\due north", &x) or past calculation 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 earlier deciding so. fgets() can read from any file stream just scanf() merely reads from standard input.

What is the syntax for using scanf()?

Here 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 northward, FILE* stream);

What does Scanf return in C?

Scanf returns the total number of inputs successful or EoF(End of Line) if in that location is an error.

Key Takeaways

While using the scanf() function, a very common problem is faced if it is used before an fgets() function. Considering of this issue, the fgets() office does not read some part of the input as the scanf() function leaves a newline character in the buffer. This can be solved by introducing a "\due north" in scanf() as in scanf("%d\n", &ten) or by adding getchar() later on scanf().

By Khushi Sharma

valentinodiany1971.blogspot.com

Source: https://www.codingninjas.com/blog/2021/07/27/solved-the-problem-with-using-fgets-after-scanf/

0 Response to "Using Fgets to Not Read New Line"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel