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

关于文件输入流的一道题目

wylog 发布于 2008-08-11 16:22, 749 次点击
编写一个程序,从一个文本文档中读取捐款的的人数,名字已经捐款的数目,并从屏幕上输出。文本文档的内容如下:
4
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Rich Raptor
55000
注:首行为捐款人数。在下面的每一对中,第一行是名字,第二行是捐款数额。要求使用结构数组进行存储每对的信息。读取所有数据后,程序将显示捐款超过10000的捐款者的姓名及捐款数额。

我遇到的困难是,声明一个结构数组后,怎样从文件区分每行的字符和数字?或者什么时候回车之后开始读取一行,例如,读取第一个数字“4”之后,怎样开始另起一行读取,然后把这行存储在一个数组里。程序主要应用ifstream对文件的读取。
3 回复
#2
xlh52252008-08-11 21:24
类的定义:
class DonativeInfo{
    friend ifstream& operator >>(ifstream& in, DonativeInfo& di){
        getline(in, di.m_name);

        string tStr;
        getline(in, tStr);
        di.m_num = atoi(tStr.c_str());

        return in;
    }
    
public:
    int    GetNum()const  {return m_num;}
    string GetName()const {return m_name;}

private:
    string  m_name;
    int     m_num;
};

所需头文件:
#include <iostream>
#include <fstream>
#include <string>

命名空间:
std

主程序:

int main(){
    ifstream fin("in.txt");
    
    int totalNum;
    string tStr;
    getline(fin, tStr);

    totalNum = atoi(tStr.c_str());

    DonativeInfo *pDI = new DonativeInfo[totalNum];
    
    for(int idx=0; idx<totalNum; ++idx)
        fin >> pDI[idx];

    cout << endl << "捐款数大于等于10000的捐款人如下:" << endl << endl;
         cout << "姓名" << "\t\t\t" << "数目" << endl;
    
    for(idx=0; idx<totalNum; ++idx){
       if(pDI[idx].GetNum() >= 10000)
    cout << pDI[idx].GetName() << "\t\t" << pDI[idx].GetNum() << endl;
    }

    cout << endl;
    delete [] pDI;

    return 0;
}
#3
xlh52252008-08-11 21:26
有一点要注意:getline和流的重载操作符>>不要混用,这样会改变流的状态...
#4
wylog2008-08-25 01:40
atoi(tStr.c_str())
哦 原来关键是我没有考虑用atoi吧
1