C++文件读写

文本文件读取

//read timestamps and poses equal to timestamps
    std::ifstream infile;
    infile.open(file_path);
    while (!infile.eof() && infile.good())
    {
        std::string line;
        std::getline(infile, line);

        if (!line.empty())
        {
            Eigen::Matrix4f pose;
            double time_stamp;
            ParseLine(line, pose, time_stamp);
        }
    }

 从字符串中解析出double.

格式: 1.1,2.1,3.1

bool PoseGenerator::ParseLine(const std::string &line, Eigen::Matrix4f &pose, double &time_stamp)
{
    if (line.size() < 1U) {
        return false;
    }
    if (line[0] == '#') {
        return false;
    }
    // 1403715274302142976,0.878612,2.142470,0.947262,0.060514,-0.828459,-0.058956,-0.553641,0.009474,-0.014009,-0.002145,-0.002229,0.020700,0.076350,-0.012492,0.547666,0.069073
    Eigen::Quaternionf q;
    Eigen::Vector3f p;
    std::istringstream iss(line);
    char dotc = ',';
    iss >> time_stamp >> dotc >> p.x() >> dotc >> p.y() >> dotc >> p.z() >> dotc >> q.w() >> dotc >> q.x() >> dotc >> q.y() >> dotc >> q.z();
//    std::cout << time_stamp << ", " << p.y() <<  ", " << q.z() << "\n"; // "\n";
    pose = Eigen::Matrix4f::Identity();
    pose.block<3, 3>(0, 0) = q.toRotationMatrix();
    pose.block<3, 1>(0, 3) = p;
    time_stamp = time_stamp / 1e9; // transform to seconds
}

以上方式处理不了如下格式

1.1 2.1 3.1 

可以使用下述方式读取:

    Eigen::Quaternionf q;
    Eigen::Vector3f p;
    std::istringstream iss(line);
    if (data_set_type_ == DATATYPE::EUROC) {
        char dotc = ',';
        iss >> time_stamp >> dotc >> p.x() >> dotc >> p.y() >> dotc >> p.z() >> dotc >> q.w() >> dotc >> q.x() >> dotc >> q.y() >> dotc >> q.z();
        time_stamp = time_stamp / 1e9; // transform to seconds
    } else if (data_set_type_ == DATATYPE::VR) {
        std::vector<std::string> strs;
        std::string spacestr;
        while (iss >> spacestr) {
            strs.emplace_back(spacestr);
        }
        time_stamp = std::atof(strs[0].c_str());
        p.x() = std::atof(strs[1].c_str());
        p.y() = std::atof(strs[2].c_str());
        p.z() = std::atof(strs[3].c_str());
        q.x() = std::atof(strs[4].c_str());
        q.y() = std::atof(strs[5].c_str());
        q.z() = std::atof(strs[6].c_str());
        q.w() = std::atof(strs[7].c_str());
//        iss >> time_stamp >> spacestr >> p.x() >> spacestr >> p.y() >> spacestr >> p.z() >> spacestr >> q.x() >> spacestr >> q.y() >> spacestr >> q.z() >> spacestr >> q.w();
    }

C++ ofstream和ifstream详细用法_Happinesspills的博客-CSDN博客_c++ ofstream

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

手持电烙铁的侠客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值