我有两个输入案例,我想使用相同的方法。 第一种情况是给定的参数是一个 std::string,其中包含我需要将其转换为 int 的三个数字:
std::string pointLine = "1 1 1";
第二种情况是给定的参数是一个 std::string,其中包含三个我需要将其转换为 double 的“尚未 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 的行。
所以我尝试了解决方案 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;
最佳答案
您可以直接从迭代器初始化 vector ,而不是复制。
// 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"
关于c++ - 如何将包含 double 的 std::string 转换为 double vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25444449/