Accepting Input from User

Accepting Input from User : There are two different ways to accept input from user

1) Accepting input from standard input/output console : Here we first display some message to user about what should be entered as input and then we accept it using scanf (). Scanf() is a built-in function of C language which accepts input.

Syntax:
scanf("formatspecifier",&var_name);

Where format specifier specifies data type of input like %d indicates data is in integer format, %c means data in character, %f means data is float values etc.

Let's consider simple C program to calculate addition of two integers given by user

#include<studio.h>
int main()
{
   int n1,n2,result;
   //to display message to user
   printf("Enter two numbers :");

   /*accepting two numbers using single scanf statement*/
   Scanf("%d%d",&n1,&n2);
   result = n1 + n2;
   //display addition of numbers
   printf("The addition entered numbers is : ",result);
return 0;
}


2) Accepting input from command line :


  • We can accept input from user as a command line argument also.
  •  In this method inputs accepted are passed as an argument to our main function thus definition of main function changes.

    • We write int main(int argc, char *argv[]){} where first parameter to main function stores count of arguments passed from the command and second argument is array which stores actual values of arguments.
    • Let's write same program written above by using command line arguments.

    #include<studio.h>
    int main(int argc,char *argv[])
    {
       int result;

       /* as integers are read char * from command line it must be converted to type integer using atoi()*/

       int n1= atoi(argv[1]);
       int n2=atoi(argv[2]);

       result = n1 + n2;

       //display addition of numbers
       printf("The addition entered numbers is : ",result);
    return 0;
    }

    Note :  To run program command should be ./a.out arg1 arg2
    For example ./a.out 56 89
    Here ./a.out will be considered as first argument and stored at argv[0] ,thus 56 and 89 will be at argv[1] and argv[2] respectively. 

    Comments

    Popular posts from this blog

    Write a program to allocate memory dynamically for n integers. Accept the elements and calculate their sum and average

    C program to accept names of n cities and search for city named “Pune”.