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;
}




Friday, January 18, 2013

Basic examples of using argc and argv[]



#include <iostream>

using namespace std;

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

cout << "argc :" << argc << endl;

for(int i=0;i<argc;i++){
    cout << "argv[" << i << "]: " << argv[i] << endl;
}

return 0;
}

I'm using Visual Studio 2012. After build solution (Ctrl+Shift+b), you will find a debug folder under you project folder. Find out the path of the application you just built, then you will be able to run it using windows cmd.
At the command line, type C:\path\Debug\application.exe one 2 three, the output will be:
argc: 4
argv[0]: C:\path\Debug\application.exe
argv[1]: one
argv[2]: 2
argv[3]: three