代码
#include <iostream>
#include <sstream>
#include <vector>
std::vector<double> string_split(std::string str, std::string split=",")
{
std::vector<double> ret_vec;
size_t pos = 0;
double num = 0;
while ((pos = str.find(split)) != std::string::npos) {
num = atof(str.substr(0, pos).c_str());
ret_vec.push_back(num);
str.erase(0, pos + split.length());
}
ret_vec.push_back(atof(str.substr(0, pos).c_str()));
return ret_vec;
}
std::ostream& operator<<(std::ostream& cout, std::vector<double> vec)
{
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
cout << std::endl;
return cout;
}
int main(void)
{
std::string str = "1.2, 3.4, 4.5, 5.6";
std::vector<double> vec = string_split(str);
std::cout << vec;
return 0;
}
输出
1.2 3.4 4.5 5.6
参考
【1】字符串划分 【2】字符串转数字
|