我试图在C++中获取一个LPSTR,例如"12,30,57“,然后将从拆分操作返回的所有数字(它们都是非十进制的)加到一个长值中。
我可以向你保证这不是家庭作业。这是我正在编写的一个扩展,它要求我在C++中编写过程性的东西,因为主dev环境不支持函数。我是一个Java/C#开发人员,所以这一切都是个谜。注:这是纯C++,而不是C++.NET。我最终将不得不用Objective编写一个版本(哦joy),所以尽可能多地兼容ANSI++,我会越好越好。
答案
我只想感谢大家的帮助,并与您分享我的代码,这是非常出色的工作。这对我来说是一个很大的负担,因为我并不是一个真正的C++家伙。但是谢谢大家。
// 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;发布于 2011-11-02 10:16:15
// 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;发布于 2011-11-02 08:54:49
有一种简单的方法(有很多,有些或多或少是有效率的):
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;发布于 2011-11-02 09:34:27
在这样一个理想的世界里,你可以做到这一点:
#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;
}相同的代码将在目标-C++中工作。
https://stackoverflow.com/questions/7977589
复制相似问题