第一种情况是给定的参数是一个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> headersstd::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 – 如何将包含双精度的std :: string转换为双精度矢量?全部内容,希望文章能够帮你解决c – 如何将包含双精度的std :: string转换为双精度矢量?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)