C++ 循環讀取文件中的字符串和數字

循環讀取文件中的字符串和數字

題目

編寫一個程序,記錄捐助給“維護合法權利團體”的資金。
該程序要求從文件中讀取捐獻者數目,和每一個捐獻者的姓名和款項。
這些信息被儲存在一個動態分配的結構數組中。
每個結構有兩個成員:
用來儲存姓名的字符數組(或string對象)和用來存儲款項的double成員。
讀取所有的數據後,程序將顯示所有捐款超過10000的捐款者的姓名及其捐款數額。
該列表前應包含一個標題,指出下面的捐款者是重要捐款人(Grand Patrons)。
然後,程序將列出其他的捐款者,該列表要以Patrons開頭。
如果某種類別沒有捐款者,則程序將打印單詞“none”。
該程序只顯示這兩種類別,而不進行排序。

讀取的文件格式

4
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Rich Raptor
55000

代碼

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int nameSize = 50;
struct donate {
    string name;
    int money;
};
int main()
{
    char filename[20];
    ifstream inFile;
    cout << "Enter name of data file: ";
    cin.getline(filename, 20);
    inFile.open(filename);
    if (!inFile.is_open())
    {
        cout << "Could not open the file " << filename << endl;
        cout << "Program terminating.\n";
        exit(EXIT_FAILURE);
    }
  
    int num = 0;
    inFile >> num;
    inFile.get();
    donate *dd = new donate[num];
    for (int i = 0; i < num; i++)
    {    
        getline(inFile, dd[i].name);
  
        inFile >> dd[i].money;
        inFile.get();
    }
// 檢測文件是否成功
    if (inFile.eof())
    {
        cout << "End of file reached.\n";
    }
    else if (inFile.fail())
        cout << "Input terminated by data mismatch.\n";
    else
        cout << "Input terminated for unknown reason.\n";
    inFile.close();
// 打印結果
    cout << "*******************Grand Patrons*******************" << endl;
    int flag = 0;
    for (int i = 0; i < num; i++)
    {
        if (dd[i].money > 10000)
        {
             cout << dd[i].name << ":\t" << dd[i].money << endl;
            flag = 1;
        }    
    }
    if (flag == 0)
    {
        cout << "none!" << endl;
    }
    cout << "*****************Grand Patrons END******************" << endl;
    cout << "*******************Patrons**************" << endl;
    flag = 0;
    for (int i = 0; i < num; i++)
    {
        if (dd[i].money <= 10000)
        {
            cout << dd[i].name << ":\t" << dd[i].money << endl;
            flag = 1;
        }
    }
    if (flag == 0)
    {
        cout << "none!" << endl;
    }
    cout << "*******************Patrons END**************" << endl;
    system("pause");	//window使用後暫停
    return 0;
}
發佈了14 篇原創文章 · 獲贊 13 · 訪問量 5661
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章