209k views
0 votes
Write a C++ program that takes two numbers from the command line and perform and arithmetic operations with them. Additionally your program must be able to take three command line arguments where if the last argument is 'a' an addition is performed, and if 's' then subtraction is performed with the first two arguments. Do not use 'cin' or gets() type functions. Do not for user input. All input must be specified on the command line separated by blank spaces (i.e. use the argv and argc input parameters).

User Bobthecow
by
5.0k points

1 Answer

1 vote

Answer:

Here is code in C++.

// include header

#include <bits/stdc++.h>

using namespace std;

//main function with command line argument as parameter

int main(int argc, char *argv[])

{

//extract all the arguments

int frstNumb = atoi(argv[1]);

int scndNumb = atoi(argv[2]);

string argv3 = argv[3];

//print all command line arguments

cout<<"first command line argument is: "<<argv[1]<<endl;

cout<<"second command line argument is: "<<argv[2]<<endl;

cout<<"third command line argument is: "<<argv[3]<<endl;

// if third argument is 'a' then addition of first two argument

if(argv3=="a")

{

int sum=frstNumb+scndNumb;

cout<<"addition of two number is:"<<sum<<endl;

}

//// if third argument is 's' then subtraction of first two argument

else if(argv3=="s")

{

int diff=frstNumb-scndNumb;

cout<<"subtraction of two number is:"<<diff<<endl;

}

//invalid input

else

cout<<"invalid command line argument:"<<endl;

return 0;

}

Step-by-step explanation:

Pass three command line arguments in the main function. Extracts all the argument. If the third argument is "a" then it will perform addition of first two arguments.If the third argument is "s" then it will perform subtraction of first two arguments.

Output:

first command line argument is: 3

second command line argument is: 4

third command line argument is: a

addition of two number is:7

Write a C++ program that takes two numbers from the command line and perform and arithmetic-example-1
User Shalmanese
by
5.3k points