使用包含双引号空格的参数调用std :: system

时间:2017-03-20 06:50:21

标签: linux c++11

我需要使用参数调用linux std :: system调用,而不是包含带空格的字符串。为了使用argc / argv正确处理它,我想用双引号传递它。

  

std :: string cmdline =“myprogram -d \”我是一个刺痛的“”;

如果我输入这个字符串,我会得到很好的结果。

当我发送到std::system(cmdline)时 看看ps -ef我得到了 myprogram -d我是一个字符串

如何将“我是一个字符串”作为myprogram的单个参数?

1 个答案:

答案 0 :(得分:1)

没问题:

dlaru@IKH-LAPTOP /cygdrive/c/Users/dlaru
$ cat test.cpp
#include <iostream>
#include <string>
#include <cstdlib>
int main()
{
        std::string cmdline = "./see \"I am a string\"";
        std::cout << cmdline << std::endl;
        std::system(cmdline.c_str());
}

dlaru@IKH-LAPTOP /cygdrive/c/Users/dlaru
$ cat see.cpp
#include <iostream>
int main(int argc, char* argv[])
{
        for (int i = 0; i < argc; ++i)
        {
                std::cout << argv[i] << std::endl;
        }
}

dlaru@IKH-LAPTOP /cygdrive/c/Users/dlaru
$ g++ -std=c++11 test.cpp -o test

dlaru@IKH-LAPTOP /cygdrive/c/Users/dlaru
$ g++ -std=c++11 see.cpp -o see

dlaru@IKH-LAPTOP /cygdrive/c/Users/dlaru
$ ./test
./see "I am a string"
./see
I am a string

(在Cygwin中测试)

相关问题