Вопрос

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;
Это было полезно?

Решение 4

// 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;

Другие советы

one simple way (there are many, some more or less efficient):

LPSTR urcstring = "12,30,57";
std::stringstream ss(urcstring);
long n,m,p; 
char comma;

ss >> n;
ss >> comma;
ss >> m;
ss >> comma;
ss >> p;

std::cout << "sum: " << ( n + m +p ) << std::endl;

In an ideal world where you have boost available you could do this:

#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
typedef char* LPSTR;

int total(LPSTR input)
{
    std::vector<std::string> parts;
    std::string inputString(input);
    boost::split(parts, inputString, boost::algorithm::is_any_of(","));
    int total = 0;
    for(size_t i = 0 ; i < parts.size() ; ++i)
        total += boost::lexical_cast<int>(parts[i]);

    return total;
}

The same code will work in Objective-C++.

Given that you need to convert the substrings to long anyway, the simplest solution is probably something like:

std::vector<long> results;
std::istringstream source(originalString);
long value;
while ( source >> value ) {
    results.push_back( value );
    char sep;
    source >> sep;
    if ( sep != ',' ) {
        source.setstate( std::ios_base::failbit );
    }
}
if ( ! source.eof() ) {
    //  Format error in input...
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top