badnack
badnack

Reputation: 767

Quotes and argv in c/c++

I've seen that the array argv (in c/c++ programs) contains strings which has been strippde by quotes.

So for example, considering the following program:

 #include <iostream>
 using namespace std;

 int main (int argc, char* argv[]) {
      cout << argv[1];
 }

When I execute it:

 ./prog 'asd'

I receive:

 asd

Is there a way to know wheter a certain parameter were stripped by the quotes (singular or double) in linux, without escaping them (like suggested here how to prevent losing double quotes in argv?)?

Upvotes: 3

Views: 3842

Answers (3)

vsoftco
vsoftco

Reputation: 56547

It is not the C++ runtime that strips the quotes from your string, but the operating system shell (like e.g. Bash). It is the latter that effectively passes the arguments to your program. So, you need to follow the rules of the shell. For example, in Bash, you need to "escape" the quotes

./prog \"something\"

because the quotes have special meaning. There is no way of "enforcing" the quotes from inside your C++ program, as they are stripped before you run your program.

Upvotes: 6

rabinnh
rabinnh

Reputation: 178

This actually has nothing to do with C/C++ stripping the quotes. It's the shell (I assume you are using *nix because of the ./prog).

Try this;

echo 'asd'

You won't see any quotes. Quotes enclose an expression so the shell can parse arguments. If you type:

echo '"asd"'

Then the outer quotes tell the shell that that whatever is inside is a literal expression.

echo "'asd'"

Upvotes: 1

John3136
John3136

Reputation: 29266

Not really. The shell actually strips the quotes, not C or C++. It's safe to assume that any member of argv that contain whitespace was originally quoted. If it doesn't contain whitespace then there is no way to know.

Upvotes: 1

Related Questions