c++: argv包含一些空格

c++: argv contains some spaces

本文关键字:空格 包含一 argv c++      更新时间:2023-10-16

我只想传递一个包含一些空格的参数到我的函数main。下面是一个例子:

string param = "{"abc" "de"}"; // the string is {"abc" "de"}
boost::replace_all(param, """, "\""); // now it becomes: {"abc" "de"}
boost::replace_all(param, " ", "\40");  // now it becomes: {"abc"40"de"}
ShellExecute(GetDesktopWindow(), "open", "myMainTest.exe", param.c_str(), "", SW_SHOWNORMAL); // execute my function main in another project

//myMainTest.exe的main函数

cout<<argv[1];

我得到了这个结果:

{"abc"40"de"}

表示双引号可以,但空格不行。

恕我直言,这与windows处理命令行的方式直接相关。参数通常用空格分隔,但用双引号括起来的字符串(")在去掉引号后会作为单个参数处理。

但它与类unix shell处理输入的方式相去甚远!没有简单直接的方法来转义引用本身。但如果你的报价是平衡的,它就会起作用。这是必须传递给ShellExecute的实际字符串:"{"abc" "def"}"。现在只剩下如何写那是c++源码:

string param = ""{\"abc\" \"def\"}"";
ShellExecute(GetDesktopWindow(), "open", "myMainTest.exe", param.c_str(), "", SW_SHOWNORMAL);

myMainTest.exe只能看到单个参数:{"abc" "def"}