我试图在嵌套循环中使用strtok().但这并没有给我预期的结果.可能是因为他们使用相同的内存位置.我的代码形式如下: -
char *token1 = strtok(Str1, "%");
while(token1 != NULL )
{
char *token2 = strtok(Str2, "%");
while(token2 != NULL )
{
//DO SMTHING
token2 = strtok(NULL, "%");
}
token1 = strtok(NULL, "%");
// Do something more
}
Run Code Online (Sandbox Code Playgroud) 我有两种输入情况,我想使用相同的方法.第一种情况是给定的参数是一个std :: string,包含三个数字,我需要转换为int:
std::string pointLine = "1 1 1";
Run Code Online (Sandbox Code Playgroud)
第二种情况是给定参数是一个std :: string,其中包含三个"not yet double",我需要将其转换为双精度数:
std::string pointLine = "1.23 23.456 3.4567"
Run Code Online (Sandbox Code Playgroud)
我写了以下方法:
std::vector<double> getVertexIndices(std::string pointLine) {
vector<int> vertVec;
vertVec.push_back((int) pointLine.at(0));
vertVec.push_back((int) pointLine.at(2));
vertVec.push_back((int) pointLine.at(4));
return vertVec;
Run Code Online (Sandbox Code Playgroud)
}
这适用于第一种情况,但不适用于应该转换为双精度的行.
于是,我的解决方案在C型双分裂.我知道我的分隔符是"".
这就是我现在想出来的,但是在第一次调用以下方法后程序崩溃了:
std::vector<double> getVertexIndices(std::string pointLine) {
vector<double> vertVec;
char * result = std::strtok(const_cast<char*>(pointLine.c_str()), " ");
while(result != NULL ) {
double vert = atof (result);
vertVec.push_back(vert);
char * result = std::strtok(NULL, " ");
}
return vertVec;
Run Code Online (Sandbox Code Playgroud)
}