怎么从文件中读这样的数据 ?

时间:2008-05-26 11:10:20   来源:论坛整理  作者:  编辑:chinaitzhe
我的问题是:

程序中间有这样的结构,

struct student
{
int id,
string name;
string hometown;
int score;
};

自己写入文件:

1,"小明","北京",620
2,"小李","南京",630
......

我存到文件中以后,想找一个合适的方法读到一个vector中 ?
谢谢。

网友回复:用fscanf可以格式化读取的.
网友回复:
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/



#include    <iostream>

#include    <vector>

#include    <string>

#include    <fstream>

#include    <cstdlib>

using namespace std; 



struct student 

{ 

public:

    int id;

    string name; 

    string hometown; 

    int score; 

}; 



void    GetData(const char* str, student& stu)

{

    char buffer[128];

    const char *beg, *end;

    int i;

    beg = str, end = str;

    

    while (*end!=',') end  ;

    for (i = 0; beg!=end; buffer[i  ] = *beg  );

    buffer[i] = 0;

    stu.id = atol(buffer);



    while (*end  !='\"');

    beg = end;

    while (*end  !='\"');

    for (i = 0; beg!=end; buffer[i  ] = *beg  );

    buffer[i-1] = 0;

    stu.name = buffer;



    while (*end  !='\"');

    beg = end;

    while (*end  !='\"');

    for (i = 0; beg!=end; buffer[i  ] = *beg  );

    buffer[i-1] = 0;

    stu.hometown = buffer;

    

    while (*end  !=',');

    beg = end;

    for (i = 0; *beg; buffer[i  ] = *beg  );

    buffer[i] = 0;

    stu.score = atol(buffer);

}



int main(int argc, char* argv[]) 

{ 

    char buffer[1024];

    vector<student> result;

    fstream fin("data.txt", ios::in);

    while (!fin.eof()&&fin.getline(buffer, 1024))

    {

        student t;

        GetData(buffer, t);

        result.push_back(t);

    }

    for (int i = 0; i < result.size();   i)

    {

        cout << result[i].id << '\t' 

            << result[i].name << '\t'

            << result[i].hometown << '\t'

            << result[i].score << endl;

    }

    fin.close();

    return 0; 

}

1       小明    北京    620

2       小李    南京    630

Press any key to continue

 

关键字:文件,数据,

相关文章

文章评论

共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面