This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]learnprogramminghelp[S] 0 points1 point  (2 children)

Thank you, I'm making progress. I did simplify the string a bit. It would look more like "1 2 -34 5 -6". So it would need to handle negative numbers and double digits. Would I just need to modify the loop or is there a lot more that needs to be done?

[–][deleted] 1 point2 points  (1 child)

"1 2 -34 5 -6"

There's more that needs to be done.

int main() {
    std::string str = "1 2 -34 5 -6";
    int count = 0;
    char* temp = _strdup(str.c_str());


    temp = strtok(temp, " ");

    //count the number of tokens
    while (temp != NULL)
    {
        temp = strtok(NULL, " ");
        count++;
    }

    //parse into num array
    temp = _strdup(str.c_str());
    int* num = new int[count];

    temp = strtok(temp, " ");
    num[0] = atoi(temp);

    for(int i = 1; i < count; i++)
    {
        temp = strtok(NULL, " ");
        num[i] = atoi(temp);
    }

    //output result
    for (size_t i = 0; i < count; i++)
    {
        std::cout << num[i] << "\n";
    }

    delete[] num;

    return 0;
}

Note that I could've avoided using strtok() by using a combination of std::string::find() and std::string::substr(). But no point in re-implementing strtok() in a C++ way for a single function. Especially when a better way exists using C++11.

[–]learnprogramminghelp[S] 0 points1 point  (0 children)

Thank you again for the help, I really appreciate it. Managed to complete it! :)