Command Line Parameters

May 20, 2013 at 7:17pm
Hi there,

I googled for command line parameters in C++ and founnd out that I could use argc and argv. The problem is the type of argv.

I need to read commandline params into a char-Array ( and im going to change one parameter to a char-vector ), I dont need a String or something!

char dname_ein[128]=argv[1];
gives
Error: main.cpp:80:17: Error: assignment of »char*« to »char [256]«

1
2
char key[256];
key[] = argv[2];

doesn't work as well.

PLease tell me how I can actually USE the params not as a string but as a char-Array.

I'm looking forward to hearing from you,

Lukas
Last edited on May 20, 2013 at 7:18pm
May 20, 2013 at 7:30pm
You can use them as usual pointers to char and they are indeed pointers to char.

Is it today such a strange day that there are so many stupid questions in the forum?

Why are you asking about command line parameters when you knowing nothing about character arrays?! Why are you bothing the forum instead of to read some book on C++?!!
Last edited on May 20, 2013 at 7:30pm
May 20, 2013 at 8:31pm
@vlad
You don't really have to be rude about it.

@ARMinius
I often find it convenient to just populate a vector of strings with the arguments and use that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main( int argc, char** argv )
  {
  vector <string> args( argv, argv + argc );

  cout << "The executable name is: " << args[ 0 ] << "\n";
  if (args.size() == 1)
    {
    cout << "There are no arguments.\n";
    }
  else 
    {
    cout << "The program arguments are:\n";
    for (size_t n = 1; n < args.size(); n++)
      {
      cout << n << ": " << args[ n ] << "\n";
      }
    }

  return 0;
  }

Hope this helps.
May 20, 2013 at 8:45pm
thanks for your answer, I'm gonna try that :)
May 21, 2013 at 9:24am
Thanks, it worked.

I converted the Commdn string into a char array via

1
2
3
    char *key=new char[args[3].size()+1];
    key[args[3].size()]=0;
    memcpy(key,args[3].c_str(),args[3].size());


and everything worked as it should. Thank you!
May 21, 2013 at 10:41am
I've another question: What, if I want to enter a prameter that uses spaces?

E.G. if i have an encryption Program that needs a key but mustn't ask for a key each time so it has to be a parameter, but it is necessary for the program to accept a key that contains spaces, how can i pass the program the key?
May 21, 2013 at 10:49am
You should enclose the parameter in quotation marks.
May 21, 2013 at 10:59am
tyvm :)
May 21, 2013 at 2:13pm
Wait, now I'm confused. First you convert to std::string, now you are converting back to char[]. Why are you doing this?

Moreover, it looks like you are trying to do something that is easily available to you in the form of http://www.boost.org/doc/libs/release/doc/html/program_options.html

Hope this helps.
Topic archived. No new replies allowed.