C/C++ : Passing Argument

I want create program with C/C++ with passing argument feature. We can input string, integer or float from this argument input. Create a file with name main.c and paste this code :

/*
 * main.c
 *
 *  Created on: Mar 24, 2011
 *      Author: toto
 */
#include <stdlib.h>
#include <stdio.h>
 
int main(int argc, char **argv)
{
    char *sstr1, *strint, *strfloat;
    int inpInt;
    float inpFloat;
    if(argc==4) //check input number of input parameter
    {
      // get argument input
      sstr1 = argv[1];
      strint = argv[2];
      strfloat = argv[3];
      
      sscanf(strint,"%i", &inpInt); //convert string to integer
      sscanf(strfloat,"%f", &inpFloat); //convert string to float
      
      //display output
      printf("string=%s \n",sstr1);
      printf("int=%i \n",inpInt);
      printf("float=%f \n",inpFloat);
    }
    return (1);
}

Compile this code with command :

gcc main.c -o cpassingarg

This is output from this program :

toto@toto-laptop:~/Documents$ ./cpassingarg string 20 5.123
string=string 
int=20 
float=5.123000

This is an example how to create program with C/C++ with passing argument feature. We can convert string to other type (string to integer, string to float) with sscanf command.

Add a Comment

Your email address will not be published. Required fields are marked *