Saturday, January 19, 2013

argc and argv[] simple programs

Now we can make some simple programs using argc and argv[].
1: ADD, num1 + num2. If we type in C:\path\Debug\ADD 2 3 at the command line, the output will be 5. If you input more than two numbers an error will be displayed. Let's just assume argv[1] and argv[2] are both integers.


#include <iostream>
using namespace std;

int main(int argc, char* argv[]){
if(argc != 3)
cout << "Format is not correct. Please enter: ADD num1 num2" << endl;
else{
cout << "ADD: num1 + num2 = " << atoi(argv[1]) + atoi(argv[2]) << endl;
}
return 0;
}


2. SUB, num1 - num2.


#include <iostream>
using namespace std;

int main(int argc, char* argv[]){
if(argc != 3)
cout << "Format is not correct. Please enter: SUB num1 num2" << endl;
else{
cout << "SUBTRACT: num1 - num2 = " << atoi(argv[1]) - atoi(argv[2]) << endl;
}
return 0;
}


3. MUL, num1 * num2.


#include <iostream>
using namespace std;

int main(int argc, char* argv[]){
if(argc != 3)
cout << "Format is not correct. Please enter: MUL num1 num2" << endl;
else{
cout << "MULTIPLY: num1 * num2 = " << atoi(argv[1]) * atoi(argv[2]) << endl;
}
return 0;
}


4. DIV, num1 \ num2. num2 cannot be 0, or an error will be displayed


#include <iostream>
using namespace std;

int main(int argc, char* argv[]){
if(argc != 3)
cout << "Format is not correct. Please enter: DIV num1 num2" << endl;
else{
if (atoi(argv[2]) == 0)
cout << "error: num2 cannot be 0" << endl;
else
cout << "DIV: num1 / num2 = " << atoi(argv[1]) / atoi(argv[2]) << endl;
}
return 0;
}




No comments:

Post a Comment