我需要阅读文本文件并将它们插入到向量中。我将其写入vector<KeyPoint>
文本文件,如下所示:
vector<KeyPoint> kp_object;
std::fstream outputFile;
outputFile.open( "myFile.txt", std::ios::out ) ;
for( size_t ii = 0; ii < kp_object.size( ); ++ii ){
outputFile << kp_object[ii].pt.x << " " << kp_object[ii].pt.y <<std::endl;
}
outputFile.close( );
当我将向量写入文件时,它看起来像这样:
121.812 223.574
157.073 106.449
119.817 172.674
112.32 102.002
214.021 133.875
147.584 132.68
180.764 107.279
每行用空格隔开。
但我无法阅读并将内容插入回向量。以下代码在读取内容并将其插入向量时出现错误。
std::ifstream file("myFile.txt");
std::string str;
int i = 0;
while (std::getline(file, str))
{
istringstream iss(str);
vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter<vector<string> >(tokens));
std::string fist = tokens.front();
std::string end = tokens.back();
double dfirst = ::atof(fist.c_str());
double dend = ::atof(end.c_str());
kp_object1[i].pt.x = dfirst;
kp_object1[i].pt.y = dend;
++i;
}