views:

1353

answers:

5

I am unable to pass integer value through the command line in turbo c++. Please help me.

+5  A: 

You'll have to pass it through as a string, and then parse it with something like atoi or strtol.

Command line arguments are always strings (or char*s if you want to be picky :)

Jon Skeet
not what @Kumar wanted, but worth mentioning for future reference: `atof` (convert string to float), `strtoul` (convert string to unsigned long), `atol` (convert string to long int), and `strtod` (convert string to double)
geowa4
+5  A: 

You cannot pass integers from the command line, only strings. Pass in your number, and use ::atoi (or any other conversion function) to convert it to an integer

Traveling Tech Guy
A: 

If you're passing it in just for this one time, and you don't need to maintain the parameters you can give your main function, you can convert the char* parameters the C++ runtime provides your program with by using int i = atoi( argv[1] ).

If you're going to have more parameters, you probably want some way to name them, too. Then it's worth taking a look at the getopt function. This one allows for more flexible command line parameters.

There even are command-line parsing frameworks out there that allow for type-checking and the lot.

xtofl
+5  A: 

You can pass arguments to executable only as strings. You could use atoi to convert string to integer.

int main(int argc, const char* argv[])
{
  if ( argc > 1 ) {
    int i = atoi( argv[1] );
  }

  return 0;
}
Kirill V. Lyadvinsky
+1  A: 

Hello,

I really wonder why you are still sticking to the ancient compiler! The sooner you switch to modern compilers the better it is! Anyways the code for doing that is below:

#include<stdlib.h>
#include<iostream.h>
int main(int lenArgs, char *args[]){
    int num = 0;
    if (lenArgs > 1){
        num = atoi(args[1]);
    }
    else{
        cout<<"Please give an argument to the program!";
        return 1;
    }
    cout<<num<<endl;
    return 0;
}