| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2368 人关注过本帖
标题:求助,如何按格式读取dat文件里面的内容
只看楼主 加入收藏
heyyroup
Rank: 1
等 级:新手上路
帖 子:77
专家分:0
注 册:2006-6-14
收藏
 问题点数:0 回复次数:1 
求助,如何按格式读取dat文件里面的内容
大家帮我看看,应该怎么实现
文件source.dat中存放一下数据
0 7754.124999 7755.223222 155.23455
1 7723.223453 7763.122222 154.89900
.......类似格式就不多写了
现在希望读取文件内的内容。并把它保存到一个结构体数组中,应该如何实现。该结构体定义如下。
struct Tpoint
{
   int  P_ID;
   float x,y,z;
}

以下是我的代码。希望大家指点以下,哪里出错了,应该如何改
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <vector>
#include <algorithm>


using namespace std;

struct Tpoint
{
    int p_ID;
    float x,y,z;
};

void OutPut(Tpoint & tp);
int main()
{
    cout << fixed << right;
    ifstream in_file;
    in_file.open("sourcefile.dat",ios_base::in|ios_base::binary);
    vector<Tpoint> point;
    if (in_file.is_open())
    {
        Tpoint tp;
        while (in_file.read((char *)&tp, sizeof(tp)))
        {
            point.push_back(tp);
        }
    }
    in_file.close();
    for_each(point.begin(), point.end(), OutPut);
    
    return 0;
}

void OutPut(Tpoint & tp)
{
    cout << setw(12) << tp.p_ID << setw(20) << tp.x
        << setw(20) << tp.y << setw(20) << tp.z << endl;
}
搜索更多相关主题的帖子: dat 格式 文件 
2008-10-18 14:22
debroa723
Rank: 10Rank: 10Rank: 10
等 级:贵宾
威 望:23
帖 子:862
专家分:1954
注 册:2008-10-12
收藏
得分:0 
in_file.read((char *)&tp, sizeof(tp))读出的是字符串,不是float类型的数.
先读出来保存到临时的字串数组里,然后根据浮点数之间有空格来截取浮点数字串,然后将截取的字串转换成浮点数(有相关的API,好象是 atof 或是 wtof 什么的,自己查一查.注意文件的格式,是多字节还是宽字节,这将决定具体使用什么函数.要不干脆自己写得了.)
里的浮点数改成字符串,读完以后,再转成浮点数.
2008-10-20 00:13
快速回复:求助,如何按格式读取dat文件里面的内容
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015116 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved