开发者

copying program arguments to a whitespace separated std::string

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


How about this:

int main(int argc, char* argv[])
{
    std::string path;
    if(argc < 2)
    {
        std::cout << "Not enough arguments" << std::endl;
        return;
    }
    path = argv[1]; // Assignment works from char* types
    // Do the rest of your folder manipulation below here
}

That should work. Even with the main() function declared as it is now, it should still work from a TCHAR (I think), or you can change main's declaration to a more "standard" main() declaration.


if my program is called as foo.exe \Program Files, then my folder string below would contain \Program Files

And when your program is called with two distinct arguments foo arg1 arg2, then you want the string to be arg1 arg2, too?

The usual way to handle this is to call the program properly in the first place:

foo "\Program Files"

This will make argv[1] contain "\Program Files".


First, notice Thomas's comment - his point is a very important one.

Now, you could find the length of your arguments and make them into one string with that size, as so (note my c++ syntax might be a little off, but the concept is there :) )

int length = 0;
for(int i = 1; i < argc; i++) {
    length += strlen(argv[i]);
}
// now add one for each require space
length += argc-2;

char* fullString = new char[length];
int ptr = 0;
for(int i = 1; i < argc; i++) {
    int strlen = strlen(argv[i]);
    for(int j = 0; j < strlen; j++) {
        fullString[ptr] = argv[i][j];
        ptr++;
    }
    fullString[ptr] = ' ';
    ptr++;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜