【问题标题】:Reading a text file using C++使用 C++ 读取文本文件
【发布时间】:2013-10-01 01:55:53
【问题描述】:

我需要读取文本文件并将它们插入到向量中。我将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;
    }

【问题讨论】:

  • 我想知道这一行: outputFile
  • “ ”之间有一个空格。你是对的,它们在每行中有两个值。对我展示的方式感到抱歉。
  • 你能粘贴你从编译器得到的错误信息吗?

标签: c++ opencv file-io vector


【解决方案1】:

您没有指定您遇到的错误。我怀疑当您尝试将元素“插入”到您的 std::vector&lt;KeyPoint&gt; 时会发生崩溃,但是:

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';
}

这似乎更具可读性,可能更高效,甚至添加了错误处理。

【讨论】:

    猜你喜欢
    • 2014-09-03
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多