通过命令行传递URL(C ++)

时间:2016-04-01 11:05:30

标签: c++ linux command command-line-arguments

我有c ++代码,它解析2个命令行参数并打印参数。其中一个论点是谷歌搜索的URL。我粘贴下面的代码

int main(int argc, char* argv[])
{
  std::cout << argv[1] << argv[2] << "\n";

}

当我在编译后通过命令行传递URL时,如下所示

./demo 1 https://www.google.co.in/search?sourceid=chrome-psyapi2&ion=1&espv=2&ie=UTF-8&client=ubuntu&q=size%20of%20unsigned%20char%20array%20c%2B%2B&oq=length%20of%20unsigned%20char*%20arra&aqs=chrome.4.69i57j0l5.13353j0j7

我得到输出为

[1] 8680
[2] 8681
[3] 8682
[4] 8683
[5] 8684
[6] 8685
[7] 8686
[2]   Done                    ion=1
[3]   Done                    espv=2
[4]   Done                    ie=UTF-8
[6]-  Done                    q=size%20of%20unsigned%20char%20array%20c%2B%2B

看起来字符串有一些内部分裂。有什么方法可以检索整个字符串吗?

提前谢谢你。

2 个答案:

答案 0 :(得分:1)

你必须引用它。否则,&被shell解释为&#34;在后台&#34;中调用&左侧的内容。

我有幸用echo替换你的程序。

好:

$ echo "https://www.google.co.in/search?sourceid=chrome-psyapi2&ion=1&espv=2&ie=UTF-8&client=ubuntu&q=size%20of%20unsigned%20char%20array%20c%2B%2B&oq=length%20of%20unsigned%20char*%20arra&aqs=chrome.4.69i57j0l5.13353j0j7"
https://www.google.co.in/search?sourceid=chrome-psyapi2&ion=1&espv=2&ie=UTF-8&client=ubuntu&q=size%20of%20unsigned%20char%20array%20c%2B%2B&oq=length%20of%20unsigned%20char*%20arra&aqs=chrome.4.69i57j0l5.13353j0j7

为:

$ echo https://www.google.co.in/search?sourceid=chrome-psyapi2&ion=1&espv=2&ie=UTF-8&client=ubuntu&q=size%20of%20unsigned%20char%20array%20c%2B%2B&oq=length%20of%20unsigned%20char*%20arra&aqs=chrome.4.69i57j0l5.13353j0j7
[1] 21705
[2] 21706
https://www.google.co.in/search?sourceid=chrome-psyapi2
[3] 21707
[4] 21708
[5] 21709
[6] 21710
[7] 21711
[1]   Done                    echo https://www.google.co.in/search?sourceid=chrome-psyapi2
[2]   Done                    ion=1
[3]   Done                    espv=2
[4]   Done                    ie=UTF-8
[5]   Done                    client=ubuntu
[6]-  Done                    q=size%20of%20unsigned%20char%20array%20c%2B%2B
[7]+  Done                    oq=length%20of%20unsigned%20char*%20arra

答案 1 :(得分:1)

您需要引用参数,并且应该使用单引号',以阻止shell尝试评估其中的任何内容。

您的命令行中的每个&符号都会启动后台进程。

第一个过程是./demo 1 https://www.google.co.in/search?sourceid=chrome-psyapi2,以下所有内容都是变量的分配。

您可以从输出中看到(看起来您并没有发布所有内容)

[1] 8680
[2] 8681
[3] 8682
[4] 8683
[5] 8684
[6] 8685
[7] 8686
[2]   Done                    ion=1
[3]   Done                    espv=2
[4]   Done                    ie=UTF-8
[6]-  Done                    q=size%20of%20unsigned%20char%20array%20c%2B%2B

后台进程2为ion=1(pid 8681),进程3(pid 8682)为espv=2,依此类推。