注册 登录
编程论坛 C++教室

请教分段读txt文件!

zibo 发布于 2008-12-13 15:58, 1355 次点击
最近读一格TXT文件,格式是这样的
1  1
20   (接下来有20行数据)
32130   23023.45   40240.89   432492.29
....
....

1  2
18   (接下来有18行数据)
32904   92134.78   98439.48   33249.39
....
....
数据是一段一段的,怎样实现分段读啊!我想得到"32310"这一列的数据,用for循环条件怎么定阿?
请高手指点一下阿
2 回复
#2
studentm2008-12-15 18:37
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

ifstream in("temp");
void readData(int &count ,int &line);

void readData(int &count ,int &line)
{
    string r;
    getline(in , r , '\n' );
    sscanf((char*)r.c_str() ,"%d",&line );
    getline(in , r , '\n' );
    sscanf((char*)r.c_str() ,"%d",&count );
}

//ifstream in("temp");
int main()
{
    string r;
    int x;
    int count = 0;
    int line = 0;

    readData(count ,line);
            
    while( getline(in , r , '\n' ) )
    {   
        sscanf((char*)r.c_str() ,"%d",&x);
        cout<<x<<endl;
        if(1 == count--)
        {   
            cout<<"-------------------"<<endl;
            readData(count ,line);
        }
    }
    in.close();
    return 0;
}

 能够实现楼主所要的功能!

[[it] 本帖最后由 studentm 于 2008-12-16 09:20 编辑 [/it]]
#3
hitcolder2008-12-15 22:59
同问,涉及到文件的指令感觉比较难,学的时候给跳过去了
1