Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将命令行拆分为可执行文件和参数_C++_String - Fatal编程技术网

C++ 将命令行拆分为可执行文件和参数

C++ 将命令行拆分为可执行文件和参数,c++,string,C++,String,在C++03中,将命令行拆分为两个字符串的最佳方法是什么:可执行字符串和参数 例如: “\”c:\\Program Files\\MyFile.exe\”/a/b/c“=>“c:\Program Files\MyFile.exe”,“/a/b/c” “c:\\Foo\\bar.exe-t\“myfile.txt\”=>“c:\Foo\bar.exe”、“-t\”myfile.txt\” “baz.exe”量子难题“=>“baz.exe”,“量子难题” 一个好的解决方案应该同时处理引号和空格

在C++03中,将命令行拆分为两个字符串的最佳方法是什么:可执行字符串和参数

例如:

  • “\”c:\\Program Files\\MyFile.exe\”/a/b/c“=>“c:\Program Files\MyFile.exe”,“/a/b/c”

  • “c:\\Foo\\bar.exe-t\“myfile.txt\”=>“c:\Foo\bar.exe”、“-t\”myfile.txt\”

  • “baz.exe”量子难题“=>“baz.exe”,“量子难题”

一个好的解决方案应该同时处理引号和空格

这是可以接受的

我当前的(工作)解决方案:

void split_cmd( const std::string& cmd, 
                std::string* executable, 
                std::string* parameters )
{
    std::string c( cmd );
    size_t exec_end;
    boost::trim_all( c );
    if( c[ 0 ] == '\"' )
    {
        exec_end = c.find_first_of( '\"', 1 );
        if( std::string::npos != exec_end )
        {
            *executable = c.substr( 1, exec_end - 1 );
            *parameters = c.substr( exec_end + 1 );
        }
        else
        {
            *executable = c.substr( 1, exec_end );
            std::string().swap( *parameters );
        }
    }
    else
    {
        exec_end = c.find_first_of( ' ', 0 );
        if( std::string::npos != exec_end )
        {
            *executable = c.substr( 0, exec_end );
            *parameters = c.substr( exec_end + 1 );
        }
        else
        {
            *executable = c.substr( 0, exec_end );
            std::string().swap( *parameters );
        }
    }
}

由于存在的方式明显优于不存在的方式,我认为你的例子是“最佳方式”。你可以重新表述你的问题“我的方式有什么问题?”或“我如何改进我的方式?”,在这种情况下,您应该将问题转移到为什么要将可执行参数和参数作为指针而不是引用传递?这是MS Windows的问题吗?在nix系统上,您只有(int argc,char argv[])-argv[0]是可执行的,argv[1]…argv[argc-1]-参数…@piokuc:我更喜欢输出参数为非常量指针。因为必须在它们前面加一个&,所以更明显的是变量将被修改。另见:@PiotrNycz:有点。我有一个像这样的字符串,
“/Foo/Bar.exe/a/b/t”
我想把它传递给
CreateProcess
,它包含两个字符串:可执行文件和参数。由于存在的方式明显优于不存在的方式,我认为您的示例是“最佳方式”。您可以重新表述您的问题“我的方式有什么问题?”或“我如何改进我的方式?”,在这种情况下,您应该将问题转移到为什么要将可执行参数和参数作为指针而不是引用传递?这是MS Windows的问题吗?在nix系统上,您刚刚有(int-argc,char-argv[])-argv[0]是可执行的,argv[1]…argv[argc-1]-arguments…@piokuc:我更喜欢输出参数为非常量指针。因为您必须在它们前面加一个&,这使得变量将被修改更为明显。另请参见:@PiotrNycz:Sort of。我有一个类似于
“/Foo/Bar.exe/a/b/t的字符串“
我想把它传递给
CreateProcess
,它包含两个字符串:可执行文件和参数。