Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
C++ Console Program Arguments
07-12-2006, 05:15 AM (This post was last modified: 09-30-2008 02:54 AM by cmckni3.)
Post: #1
C++ Console Program Arguments
This is a tutorial I wrote about making a console program that accepts commandline arguments. I am using the standard format of
Code:
int argc, char *argv[]
but you can use different datatypes if necessary. The first argument argc is the number of parameters and the second is an array holding the values inputted into the arguments. Here is an example program I made that adds the value of two arguments and outputs their sum.
Code:
#include <iostream>

using namespace std;

int main (int argc, char *argv[])
{
  if (argc != 3)//3 arguments should be used
  {
       // We print argv[0] assuming it is the program name
       //output the usage of the program (program aguments)
       cout<<"usage: "<< argv[0] <<" <first number> <second number>\n";
   }
   else
   {
       //convert first parameter to int
       int firstparam = atoi(argv[1]);
      
       //convert second argument to int
       int secondparam = atoi(argv[2]);
      
       //add the two together
       int add = firstparam + secondparam;
      
       //output their sum
       cout<<add<<"\n";
   }
  
   //wait until key is pressed
   system("PAUSE");
  
   //return the value for the function, in this case int
   return 0;
}

I find this useful because when using Microsoft Visual Studio you can use a program that takes command line arguments and does something like write to a file.

If you like this tutorial please register.
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump: