背景:在保存文件的时候,只能做到逐行将原本的vector<Point>保存为string类型,如下:
在读取时,发现无法直接将其转换为Point形式,因此自己构建了一个函数来实现。
思路:逐行读取txt文件,每次获取的string形如[2,3],将其传入函数,函数根据ASII码上对应逗号的值,获取逗号索引,通过string的substr切片对应位置获取对应x、y值,最后用stoi函数将string转换为int。
代码:
void split(string point_str, Point &point_inf) {
int leng = point_str.size();
int comma_index = -1;
//获取逗号索引
for (int i = 0; i < leng; ++i) {
if (int(point_str[i] == 44)) {
comma_index = i;
break;
}
}
if (comma_index == -1) {
cout << "error data ,need use save_origin_feature to restore !" << endl;
}
point_inf.x = stoi(point_str.substr(1, comma_index - 1));
point_inf.y = stoi(point_str.substr(comma_index + 2, leng - comma_index - 3));
}