Getting Input from STDIN – scanf(), fgets()

Reading input from stdin, or the keyboard can be accomplished using the scanf() and getch() functions.  Let’s take a look at scanf first.

scanf()

As with other input and output functions, we must include stdio.h.  The scanf function is defined:

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

Look Familiar?  It looks a bit like printf.  In the format parameter, you enter the control string for how the user input should be formatted.  If you wanted to ask the user to input an integer, you write something like this:

 

#include <stdio.h> 
int main(int argc, char** argv) { 
     int UserNumber=0; 
     printf("Enter your number: ");  
     scanf("%d",&UserNumber); 
     printf("You typed %d\n",UserNumber); 
     return 0; 
} 

or, try asking the user for their first and last name

#include <stdio.h>
int main(int argc, char** argv) {
    
    char FirstName[255];
    char LastName[255];
    
    printf("Enter your First and Last Name: ");
    scanf("%s %s",FirstName,LastName);
    printf("Welcome %s %s\n",FirstName,LastName);

    return 0;
}

Note that scanf is looking for a specific format to be entered by the user.

 

fgets()

You may also use fgets  to get an unformatted string of text:

#include <stdio.h>
int main(int argc, char** argv) {
    
    char UserText[255];
    printf("Enter some Text: \n");
    fgets(UserText,254,stdin);

    printf("You Wrote: \n");
    printf("%s\n",UserText);
 

    return 0;
}

Note that fgets() takes 3 parameters. The first parameter is the string (character array) where you want to store the entered data.  The second parameter is the number of bytes you have allocated to store the data.  The last parameter is the stream from which to read the data.  We use stdin to read from the keyboard.