dimanche 17 juin 2018

C++ - find function does not work executed on substring

I do have got a problem with an algorithm, which I want to use to split command line into several substrings. E.g. the string "Hello World -n filename" should be sliced into "Hello" "World" and "-n filename".

Here is my whole code example:

string hello = "Hello World -n filename";
uint64_t startIndex = 0;
uint64_t endIndex = hello.length() - 1;

while(startIndex < endIndex) {
    uint64_t nextWhiteSpaceIndex;
    string value;

    if(hello.at(startIndex) != '-') {

        nextWhiteSpaceIndex = hello.substr(startIndex).find(" ");
        value = hello.substr(startIndex, nextWhiteSpaceIndex);
        cout << value << endl;

    } else {

        nextWhiteSpaceIndex = hello.substr(hello.substr(startIndex).find(" ")).find(" ");
        value = hello.substr(startIndex, nextWhiteSpaceIndex);
        cout << value << endl;

    }
    startIndex = nextWhiteSpaceIndex + 1;
}

And I do have problems with this command:

nextWhiteSpaceIndex = hello.substr(startIndex).find(" ");

This is placed within the while-loop and it seems like the...

.substr(startIndex)

... part is completely ignored. The first loop run works fine, but during the second/following the nextWhiteSpaceIndex does not get the right next index assigned. It always prints "Hello" "World" "World" "World" "World" and continues to print "World".

Do you guys have a hint, why this does not work? I could not find an appropriate explanation during my research through the web.

Aucun commentaire:

Enregistrer un commentaire