使用 C++ 读取文本文件
Reading a text file using C++
我需要读取文本文件并将它们插入到向量中。我将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;
}
您没有指定您遇到的错误。我怀疑当您尝试将元素"插入"std::vector<KeyPoint>
时会出现崩溃,但是:
kp_object1[i].pt.x = dfirst;
kp_object1[i].pt.y = dend;
除非kp_object1
至少有i + 1
元素,否则这是行不通的。您可能想使用类似的东西
KeyPoint object;
object.pt.x = dfirst;
object.pt.y = dend;
kp_object1.push_back(object);
如果您的KeyPoint
具有合适的构造函数,则可以使用
kp_object1.push_back(KeyPoint(dfirst, dend));
相反。
顺便说一句,我会像这样解码各个行:
KeyPoint object;
if (std::istringstream(str) >> object.pt.x >> object.pt.y) {
kp_object1.push_back(object);
}
else {
std::cerr << "ERROR: failed to decode line '" << line << 'n';
}
这似乎更具可读性,可能更有效,甚至增加了错误处理。
相关文章:
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- C++程序不返回文件中文本和字符串数据的值
- 提升配置文件的文本文件接收器设置
- 随机访问文件格式,用于分层组织的二进制文件和文本文件
- 是否可以使头文件使文本居中?- 在控制台中
- 如何为包含其他 protobuf 的 protobuf 文件编写文本
- 使用strtok_s显示来自文本文件的文本
- 根据某些输入文件预测文本生成'random'下一个字符
- 从二进制文件中抓取文本时,为什么 xdg_vtnr=8 是我的结果
- 我怎么知道我是在读二进制文件还是文本文件
- 如何在wxWidgets的同一窗口中拖放文件和文本
- 二进制文件到文本文件,文本文件到二进制文件
- 无法从文件打印文本
- 设置新文件默认文本
- C++显示文本文件...("Echo"文本文件)
- 从Windows应用程序的文本框中抓取文本
- 音频文件到文本使用SAPI或同等功能的SR
- 对于大文件,文本文件中的大多数常用词从未完成
- 通过套接字发送文件和文本
- 从文件读取文本到无符号字符数组