c++lpstr

Split LPSTR and add up values as a long


I am trying to take an LPSTR in C++ such as "12,30,57" and split it and then add up all of the numbers (they are all non-decimal) that are returned from the split operation into a resulting long value.

This is not homework I can assure you. It's for an extension I am writing which requires that I code procedural stuff in C++ since the main dev environment does not support functions. I am a Java/C# developer so this is all a mystery. NOTE: This is pure C++ and not C++.NET. I will eventually have to write a version in Objective-C as well (oh joy) so as much ANSI-C++ compliant as possible the better off I will be.

ANSWER:

I just wanted to thank everyone for your help and share my code with you which works brilliantly. This is quite a stretch for me as I'm not really a C++ guy. But thanks everyone.

// Get
long theparam = GetSomeLPSTR(); // e.g. pointer to "1,2,3,4,5,6"

// Set
char *temp = (LPSTR)theparam;
char *temp2 = (LPSTR)malloc(strlen(temp)+1);
strcpy(temp2,temp);

long result = 0;
char * pch;

// Split
pch = strtok(temp2,",");

// Iterate
while (pch != NULL)
{
    // Add to result
    result += atoi(pch);

    // Do it again
    pch = strtok (NULL,",");
}

// Return
return result;

Solution

  • // Get
    long theparam = GetSomeLPSTR(); // e.g. pointer to "1,2,3,4,5,6"
    
    // Set
    char *temp = (LPSTR)theparam;
    char *temp2 = (LPSTR)malloc(strlen(temp)+1);
    strcpy(temp2,temp);
    
    long result = 0;
    char * pch;
    
    // Split
    pch = strtok(temp2,",");
    
    // Iterate
    while (pch != NULL)
    {
        // Add to result
        result += atoi(pch);
    
        // Do it again
        pch = strtok (NULL,",");
    }
    
    // Return
    return result;