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

Difference between Web Designer and Web Developer Neeraj Mishra The Crazy Programmer

Have you ever wondered about the distinctions between web developers’ and web designers’ duties and obligations? You’re not alone! Many people have trouble distinguishing between these two. Although they collaborate to publish new websites on the internet, web developers and web designers play very different roles. To put these job possibilities into perspective, consider the construction of a house. To create a vision for the house, including the visual components, the space planning and layout, the materials, and the overall appearance and sense of the space, you need an architect. That said, to translate an idea into a building, you need construction professionals to take those architectural drawings and put them into practice. Image Source In a similar vein, web development and design work together to create websites. Let’s examine the major responsibilities and distinctions between web developers and web designers. Let’s get going, shall we? What Does a Web Designer Do?

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 declaring 20