DrakeMcCain
DrakeMcCain

Reputation: 159

How can I pass a command line argument which contains space character to my C++ program?

We can access command line arguments via argv code in C++, I know that.

But the problem is, if an argument contains space, then my program works like as if there are two parameters.

For example if the argument is foo bar, my program sees two parameters (foo and bar).

Here is my code:

string strParameter = string(argv[1]);

So, what should I do?

Upvotes: 0

Views: 5352

Answers (2)

DrakeMcCain
DrakeMcCain

Reputation: 159

Ok, I have fixed my problem myself.

Here is my solution:

for(int i=1; i<argc; i++)
{
    strParameter = strParameter + string(argv[i]) + " ";
}

Upvotes: 0

HolyBlackCat
HolyBlackCat

Reputation: 96579

This is determined by your shell, not your program. In most shells, you can solve this either by wrapping the parameter in single and/or double quotes:

  • "foo bar"
  • 'foo bar'

or putting a special symbol before the space:

  • foo\ bar
  • foo^ bar in CMD (on Windows)

Upvotes: 5

Related Questions