copying program arguments to a whitespace separated std::string

Posted by PaulH on Stack Overflow See other posts from Stack Overflow or by PaulH
Published on 2010-05-12T16:00:04Z Indexed on 2010/05/12 16:04 UTC
Read the original article Hit count: 260

Filed under:

I have a Visual Studio 2008 C++ application where I would like to copy all of program arguments in to a string separated by a whitespace " ". i.e., if my program is called as foo.exe \Program Files, then my folder string below would contain \Program Files

Below is an example of what I'm doing now. I was wondering if there was a shorter or easier method of doing this. Is there an easy way to eliminate the std::wstringstream variable?

int _tmain( int argc, _TCHAR* argv[] )
{
    std::wstringstream f;
    std::copy( argv + 1,
               argv + argc,
               std::ostream_iterator< std::wstring, wchar_t >( f, L" " ) );
    std::wstring folder = f.str();

    // ensure the folder begins with a backslash
    if( folder[ 0 ] != L'\\' )
        folder.insert( 0, 1, L'\\' );

    // remove the trailing " " character from the end added by the std::copy() above
    if( *folder.rbegin() == L' ')
        folder.erase( folder.size() - 1 );

    // ... 
}

Thanks, PaulH

© Stack Overflow or respective owner

Related posts about c++