我有两种输入情况,我想使用相同的方法.
第一种情况是给定的参数是一个std :: string,包含三个数字,我需要转换为int:
第一种情况是给定的参数是一个std :: string,包含三个数字,我需要转换为int:
std::string pointLine = "1 1 1";
第二种情况是给定参数是一个std :: string,其中包含三个“not yet double”,我需要将其转换为双精度数:
std::string pointLine = "1.23 23.456 3.4567"
我写了以下方法:
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;
}
这适用于第一种情况,但不适用于应该转换为双精度的行.
所以我尝试了解决方案Double split in 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;
}
解决方法
您可以直接从迭代器初始化矢量,而不是复制.
// include <string>,<vector>,<iterator> and <sstream> headers
std::vector<double> getVertexIndices(std::string const& pointLine)
{
std::istringstream iss(pointLine);
return std::vector<double>{
std::istream_iterator<double>(iss),std::istream_iterator<double>()
};
}
这与您的整数完全相同.你的int-approach不会像你想要的那样用于“123 456 789”这样的字符串

