ccpp5編程練習6.9

// ex6.9
// !!!!!!!!!!!!!!!!!!!!!!
//     注意清除隊列中的換行符
// !!!!!!!!!!!!!!!!!!!!!!
// ex609.cpp:28:22: 錯誤: 對‘std::basic_ifstream<char>::open(std::string&)’的調用沒有匹配的函數

#include <iostream>
#include <fstream>
#include <cstdlib> // support for exit()
#include <string>

const int SIZE = 60;
using namespace std;
struct donor {
	string name;
	double amount;
};

int main ()
{
	char filename[SIZE];  // 就我目前的知識,不要用 string,打不開
	ifstream inFile; // object for handling file input

	cout << "Society for the Preservation of Rightful Influence.\n\n";
	cout << "Enter filename to open: ";
	cin.getline(filename, SIZE);  // 輸入文件名
		
	inFile.open(filename);   // 關聯文件
	if (!inFile.is_open())   // failed to open file
	{
		cout << "Could not open the file " << filename << endl;
		cout << "Program terminating.\n";
		exit(EXIT_FAILURE);
	}
	//------------------------------------------------
	cout << "\nSuccess, opening file " << filename;
	int num = -1; // number of contributors

	inFile >> num; // 獲取捐款人數
	if (num <= 0) {
		cout << "Bad data! num <= 0.\nexiting...\n";
		return 1;
	}

	inFile.get();   // 清除換行符

	cout << "\nThe number of donors: " << num << endl;

	donor * Mydonor = new donor [num];  // 分配內存

	// 怎樣排除各類錯誤狀況?暫時先不考慮吧。
	for (int i = 0; i < num; i++)
	{
		getline(inFile, Mydonor[i].name);
		cout << "Donor's Name #" << (i+1) << ": " << Mydonor[i].name << endl;
		(inFile >> Mydonor[i].amount).get();
		cout << "Amount #" << (i+1) << ": " << Mydonor[i].amount << endl;
	}
	 
	
	//----------------------------------------------------------
	cout << "\nGrand Patrons\n----------\n";
	int count = 0;    // 統計,檢查是否 0 個
	for (int i = 0; i < num; i++)
	{
		if (Mydonor[i].amount >= 10000)
		{
			cout << Mydonor[i].name << ": $" 
			     << Mydonor[i].amount << endl;
			++count;
		}
	}
	if (count == 0)
		cout << "none\n";

//----------------------------------------------------------
	cout << "\nPatrons\n----------\n";
	if (count < num)
	{
		for (int i = 0; i < num; i++)
		{
			if (Mydonor[i].amount < 10000)
			{
				cout << Mydonor[i].name << ": $" 
				     << Mydonor[i].amount << endl;
				++count;
			}
		}
	}
	else
		cout << "none\n";

	delete [] Mydonor;
	inFile.close();
	return 0;
}
相關文章
相關標籤/搜索