Getting input in C

                 Getting input in C


There are two ways to get input from user in C language.
1) By scanf() function
2) By gets() or fgets() function

1. By scanf() function:-

           The standard input-output header file named stdio.h  contains the definition of the function printf()  and scanf(), which are used to display on the screen and to take input from user.
  • Program:-  

#include<stdio.h>

void main()
{
    // defining a variable
    int x;
    /* 
        displaying message on the screen
        asking the user to input a value
    */
    printf("Please enter a value...");
    /*
        reading the value entered by the user
    */
    scanf("%d", &x);
    /*
        displaying the number as output
    */
    printf( "\nYou entered: %d", x);
}

  • Output:-

 Please enter a value...

The Output was asking to input.
After putting value....you will get output like below.

  • suppose  you are entering number 50
you will get output like below
 You entered:  50 
 Here %d reads only the number.

  •  suppose you are entering number 50.50.
you will get output nearest natural number like above.

Note: you can not print values like 50.50, 50.50.01...But if you want to print then use "%f" instead of %d.

you can also set character limit by adding number with %d. like %1d, %2d...
the first one means a single numeric digit, hence if you try to input 50, while scanf() has "%1d", it will take only as input.

  2. By gets() or fgets() function:-

   Scanf() stop reading character when it encounters a space but gets reads space as a character too.  
  
the syntax of gets() function is:

Syntax :  gets(string);


  • Program:-


include<stdio.h>

void main()
{
    /* character array of length 100 */
    char name[100];
    printf("Enter your name...");
    gets( name );
    puts( name );
    getch();
}

Reading function :-   gets()
Printing function:- puts()

  • Output:-
Enter your name... 

 The output will ask to get input from the user.

  • suppose you enter your name "Dee Blackbird"
you will get output like below.

Dee Blackbird

 If you enter the name as Dee Blackbird using scanf() it will only read and store Dee and will leave the part after space. But gets() function will read it completely and your output will be "Dee blackbird".

Comments

Popular posts from this blog

Unary Operator