Skip to main content

fgets() vs scanf() in C Nitish Agarwal The Crazy Programmer

In this article, we will take a look at two of the most basic functions used in the C language and subsequently, we will compare them on the basis of their usage.

Both fgets and scanf functions are used to take basic user inputs in the program. The major difference between these two functions is that the scanf function takes the input of any data type (int, float, char, double, etc.) but falls behind while taking string inputs. The reason for this behavior is that string inputs contain whitespaces and as soon as the scanf function encounters these whitespaces, it stops scanning further, thus making the function less accessible for string inputs.

While, the fgets function is used to take inputs of any data type (int, float, double, char, etc.) as well as string inputs containing whitespaces. One more major advantage of using fgets function is that it can even read input data from a specified text file or console, which the scanf function cannot. fgets function even allows us to specify the size of user input to be taken, thus making it a user-friendly function.

scanf() in C

The format to take user input using scanf function is given as:

scanf (“<format specifier>”, &<variable_name>)

The format specifier to take integer input is “%d”, for float input, it is “%f” and for string input, it is “%s”. Let us understand this concept using a sample program.

#include <stdio.h>

int main(){
        int a ;
        float b ;
        char c[100] ;
        scanf ( “%d” , &a) ;
        scanf ( “%f” , &b) ;
        scanf ( “%s” , &c) ;
        printf( “%d” , a) ;
        printf(“\n”) ;
        printf( “%f” , b) ;
        printf(“\n”) ;
        printf( “%s” , c) ;
        return 0 ;
}

Input:

3
10.23
Welcome to The Crazy Programmer

Output:

3
10.230000
Welcome

In this program, we have initialized an integer ‘a’, a float number ‘b’, and a string ‘c’. Note that the data type of string is char and the numerical part written after the string variable ‘c’ is the maximum length of the string, user can input.

As we can observe from the output, the scanf function stopped scanning the string input after it encountered whitespace and therefore, displayed only the first word of the string.

fgets() in C

To remove this error, fgets function comes in force. The format to take user input using fgets function is given as:

fgets (<string_name>, <string_size to be printed>, stdin)

Here, stdin is a keyword used to take standard input from stdin stream. To understand this better, let us see a sample program.

#include <stdio.h>

int main(){
     char str[100] ;
     fgets ( str , 40 , stdin) ;
     printf ( “%s” , str ) ;
      return 0 ;
}

Input:

Welcome to The Crazy Programmer!

Output:

Welcome to The Crazy Programmer!

Here, we notice that fgets function read the full string and didn’t stop scanning the string even after encountering whitespaces. Therefore, using fgets function for string input is advantageous and handy.

One more usage of fgets function is that it is also used to take input directly from a text file. Let us understand this using a sample program.

Consider a text file named ‘file.txt’ containing the line “Hello World!” saved in your computer system. Now, study the following program :

#include <stdio.h>

int main(){
        char str[30] ;
        FILE *fp ;
        fp = (“file.txt” , “r” ) ;              // Line 3
        fgets (str , 20 , stdin) ;              // Line 4
        printf (“%s” , str );
        fclose(fp) ;
        return 0 ;
}

Output:

Hello World!

In this program, we created a pointer to a file ‘fp’ which is used to read the content from the file. The ‘r’ keyword in Line 3 is used to read the file. In line 4, the fgets function is used to take input from the file, which will print the string up to 20 characters. Remember to close the file after reading it at the end of the program using ‘fclose’ function.

Although scanf is mostly used to take user input, it is preferable to use fgets while taking string inputs as it makes the program error-free.

The post fgets() vs scanf() in C appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3okx6LU

Comments

Popular posts from this blog

A guide to data integration tools

CData Software is a leader in data access and connectivity solutions. It specializes in the development of data drivers and data access technologies for real-time access to online or on-premise applications, databases and web APIs. The company is focused on bringing data connectivity capabilities natively into tools organizations already use. It also features ETL/ELT solutions, enterprise connectors, and data visualization. Matillion ’s data transformation software empowers customers to extract data from a wide number of sources, load it into their chosen cloud data warehouse (CDW) and transform that data from its siloed source state, into analytics-ready insights – prepared for advanced analytics, machine learning, and artificial intelligence use cases. Only Matillion is purpose-built for Snowflake, Amazon Redshift, Google BigQuery, and Microsoft Azure, enabling businesses to achieve new levels of simplicity, speed, scale, and savings. Trusted by companies of all sizes to meet...

2022: The year of hybrid work

Remote work was once considered a luxury to many, but in 2020, it became a necessity for a large portion of the workforce, as the scary and unknown COVID-19 virus sickened and even took the lives of so many people around the world.  Some workers were able to thrive in a remote setting, while others felt isolated and struggled to keep up a balance between their work and home lives. Last year saw the availability of life-saving vaccines, so companies were able to start having the conversation about what to do next. Should they keep everyone remote? Should they go back to working in the office full time? Or should they do something in between? Enter hybrid work, which offers a mix of the two. A Fall 2021 study conducted by Google revealed that over 75% of survey respondents expect hybrid work to become a standard practice within their organization within the next three years.  Thus, two years after the world abruptly shifted to widespread adoption of remote work, we are dec...

10 Simple Image Slider HTML CSS JavaScript Examples Neeraj Mishra The Crazy Programmer

Slider is a very important part of any website or web project. Here are some simple image slider examples that I handpicked from various sites. These are built by different developers using basic HTML, CSS, and JavaScript. Some are manual while others have auto-slide functionality. You can find the source code for each by clicking on the code button or on the image. 1. Very Simple Slider Demo + Code 2. Popout Slider Demo + Code 3. Really Simple Slider Demo + Code 4. Jquery Simple Slider Demo + Code 5. Manual Slideshow Demo + Code 6. Slideshow Indicators Demo + Code 7. Simple Responsive Fullscreen Slider Demo + Code 8. Responsive Image Slider Demo + Code 9. Simple Image Slider Demo + Code 10. Slicebox – 3D Image Slider Demo + Code I hope these simple image sliders are helpful for you. For any queries, you can ask in the comment section below. The post 10 Simple Image Slider HTML CSS JavaScript Examples appeared first on The Crazy Prog...