简体   繁体   English

c / c ++中的引号和argv

[英]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. 我已经看到数组argv(在c / c ++程序中)包含已被引号括起来的字符串。

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? )? 有没有办法知道某个参数是否被linux中的引号(单数或双引号)剥离,而没有转义它们(如此处建议如何防止在argv中丢失双引号? )?

It is not the C++ runtime that strips the quotes from your string, but the operating system shell (like eg Bash). C ++运行时不是从字符串中删除引号,而是操作系统shell(例如Bash)。 It is the latter that effectively passes the arguments to your program. 后者有效地将参数传递给您的程序。 So, you need to follow the rules of the shell. 所以,你需要遵循shell的规则。 For example, in Bash, you need to "escape" the quotes 例如,在Bash中,您需要“转义”引号

./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. 无法从C ++程序中“强制”引用,因为在运行程序之前它们会被删除。

Not really. 并不是的。 The shell actually strips the quotes, not C or C++. shell实际上剥离了引号,而不是C或C ++。 It's safe to assume that any member of argv that contain whitespace was originally quoted. 假设最初引用包含空格的argv任何成员是安全的。 If it doesn't contain whitespace then there is no way to know. 如果它不包含空格,则无法知道。

This actually has nothing to do with C/C++ stripping the quotes. 这实际上与C / C ++剥离引号无关。 It's the shell (I assume you are using *nix because of the ./prog). 它是shell(我假设你使用* nix因为./prog)。

Try this; 尝试这个;

echo 'asd'

You won't see any quotes. 你不会看到任何报价。 Quotes enclose an expression so the shell can parse arguments. 引号括起一个表达式,以便shell可以解析参数。 If you type: 如果输入:

echo '"asd"'

Then the outer quotes tell the shell that that whatever is inside is a literal expression. 然后外引号告诉shell,内部的任何内容都是文字表达式。

echo "'asd'"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM