c++ 分割字串
阿新 • • 發佈:2020-09-17
功能: 讀取txt檔案資料到陣列中,輸入txt檔案路徑,分隔符,輸出為陣列
#include <iostream> #include <cstring> #include <string> using namespace std; void ReadDataFromFile(string file_path, vector<Point2f>& data, string pattern) { ifstream fin(file_path); string line_info,input_result; if(fin) { while (getline (fin, line_info)) // line中不包括每行的換行符 { vector<string> vectorString; // stringstream input(line_info); // //依次輸出到input_result中,並存入vectorString中 // while(input>>input_result) // vectorString.push_back(input_result); // //convert string to float // data.emplace_back(Point2f(atof(vectorString[0].c_str()),atof(vectorString[1].c_str()))); char * cstr = new char [line_info.length()+1]; std::strcpy (cstr, line_info.c_str()); // cstr now contains a c-string copy of str char * p = std::strtok (cstr,pattern.c_str()); while (p!=0) { vectorString.push_back(p); p = std::strtok(NULL,pattern.c_str()); } delete[] cstr; data.emplace_back(Point2f(atof(vectorString[0].c_str()),atof(vectorString[1].c_str()))); } } else // 沒有該檔案 { cout<<"no such file"<<endl;; } } int main(void) { string img_0_txt = output_path + "/0.png.txt"; vector<Point2f> feature_l_2d; ReadDataFromFile(img_0_txt, feature_l_2d, " "); return 0; }