1. 程式人生 > >第六章習題——C++ Primer Plus

第六章習題——C++ Primer Plus

這是一個寫作業的系列,旨在po出執行通過的程式碼。前五章較為簡單,於是沒有寫。從第六章開始,我會完成這一系列的作業。提高自己coding的熟練度。

編譯環境:Visual Sudio 2017

1. 編寫一個程式,讀取鍵盤輸入,直到遇到@符號為止,並回顯輸入(數字除外),同時將大寫字元轉換為小寫,將小寫字元轉換為大寫(別忘了cctype函式系列)。

//6.1
#include "stdafx.h"//膝上型電腦在VS執行時應該首先加入這個標頭檔案,否則iostream無法工作
#include <iostream>
#include <cctype>
using namespace std;

int main()
{
	
	cout << "Enter data until an @ to terminate the input.\n";
	char ch;
	while (cin.get(ch) && ch != '@')
	{
		if (ch >= 'a'&&ch <= 'z')
			ch = toupper(ch);
		else if (ch >= 'A'&&ch <= 'Z')
			ch = tolower(ch);
		cout << ch;
	}
	cout << "\nInput complete.\n";
	system("pause");
    return 0;
}

2. 編寫一個程式,最多將10個donation值讀入到一個double陣列中。程式遇到非數字輸入時將結束輸入,並報告這些數字的平均值以及陣列中有多少個數字大於平均值。

#include "stdafx.h"
#include<iostream>
#include<array>
using namespace std;

int main()
{

	//double arr[10];//可以選擇使用陣列
	array<double, 10>arr;
	int i = 0, j, num;
	double sum = 0, average = 0,temp;
	cout << "輸入最多10個donation值:(非數字時將結束輸入)\n";
	while ((cin >> temp) && (i<10))
	{
		arr[i] = temp;		
		sum += arr[i++];
	}
	average = sum / i;
	for (j = 0, num = 0; j < i; j++)
	{
		if (arr[j] > average)
			num++;
	}
	cout << "平均值:" << average<< " ,有 "<< num<< " 個數字超過平均值"<< endl;
	system("pause");
	return 0;
}

3.編寫一個選單驅動程式的雛形。該程式顯示一個提供4個選項的選單——每個選項用一個字母標記。

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
	char ch;
	cout << "Please enter one of the following choices:\n";
	cout << "c)carnivore\t" << "p) pianist"<<endl;
	cout << "t)tree\t\t" << "g) game"<<endl;
	while (cin >> ch) {
		switch (ch)
		{
		case 'c':	cout << "Danger!\n";
			break;
		case 'p':	cout << "Enjoy the music.\n";
			break;
		case 't':	cout << "A maple is a tree.\n";
			break;
		case 'g':	cout << "No child don't love game!\n";
			break;
		default: cout << "Please enter a c, p, t, or g:";
			continue;
		}
	}
	system("pause");
	return 0;   
}

4. 加入Benevolent Order of Programmer後,在BOP大會上,人們便可以通過加入者的真實姓名、頭銜或祕密BOP姓名來了解他(她)。請編寫一個程式,可以使用真實姓名、頭銜、祕密姓名或成員偏好來列出成員。

#include "stdafx.h"
#include <iostream>

const int strsize = 30;
struct bop{
	char fullname[strsize];
	char title[strsize];
	char bopname[strsize];
	char preference[strsize];
};
using namespace std;
int main()
{
	bop information[5]{
		{"Wimp Macho","Professor","W.M","Wimp Macho" },
		{"Raki Rhodes", "Engineer", "Chock", "Junior Programmer" },
		{"Celia Laiter","Associate professor","Great C","MIPS"},
		{"Hoppy Hipman","Lecturer","HipHop","Analyst Trainee"},
		{ "Pat Hand","Student","RatCat","LOOPY"},
	};
	char ch;
	int i;
	cout << "a. diplay by name\t" << "b. display by title" << endl;
	cout << "c. display by bopname\t" << "d. display by preference" << endl;
	cout << "q. quit" << endl;
	cout << "Enter your choice:" ;
	while (cin>>ch&&ch != 'q')
	{
		switch(ch)
		{
			case 'a':
			for (i = 0; i < 5; i++)
				{
				cout << information[i].fullname << endl;
				}
				break;
			case 'b':
			for (i = 0; i < 5; i++)
				{
					cout << information[i].title << endl;
				}
				break;
			case 'c':
				for (i = 0; i < 5; i++)
				{
					cout << information[i].bopname << endl;
				}
				break;
			case 'd':
				for (i = 0; i < 5; i++)
				{
					cout << information[i].preference << endl;
				}
				break;
			default:
				cout << "Please recheck your input." << endl;
				cout << "Enter your choice(a,b,c,d,q)";

				continue;
		}
		cout << "Next choice:";
	}
	system("pause");
    return 0;
}

5. 在Neutronia王國,貨幣單位是tvarp,收入所得稅的計算方式如下:

5000 tvarps”:不收稅

5001~15000 tvarps:10%

15001~35000 tvarps:15%

35000以上: 20%

例如,收入為38000 tvarps時,所得稅為5000*0.00 + 10000*0.10+20000*0.15+3000*0.20,即4600tvarps。請編寫一個程式,使用迴圈來要求使用者輸入收入,並報告所得稅。當用戶輸入負數或非數字時,迴圈將結束。

寫這題的程式碼時,我將不同的納稅區間定義成了常量,便於程式的修改。

#include "stdafx.h"
#include <iostream>

const int line1 = 5000;//第一條徵稅線
const int line2 = 15000;//第二條徵稅線
const int line3 = 35000;//第一條徵稅線

const int step1 = line1;	//第一徵稅區間
const int step2 = line2 - line1;//第一徵稅區間
const int step3 = line3 - line2;//第三徵稅區間

const float rate1 = 0.00;	//第一徵稅區間稅率
const float rate2 = 0.10;	//第二徵稅區間稅率
const float rate3 = 0.15;	//第三徵稅區間稅率
const float rate4 = 0.20;   //第四徵稅區間稅率

using namespace std;
int main()
{
	int income; 
	float tax = 0;
	cout << "請輸入您的收入:";

	while (cin >> income&&income >= 0)
	{
		
		if (income > step1)
		{
			tax += step1*rate1;
			income -= step1;

			if (income > step2)
			{

				tax += step2*rate2;
				income -= step2;

				if (income > step3)
				{
					tax += step3*rate3;
					income -= step3;

					if (income > 0)
						tax += income*rate4;
				}
				else tax += income*rate3;
			}
			else tax +=  income*rate2;
		}
		else tax += income*rate1;

		cout << "經計算,您所需要繳納稅款為" << tax << "tvarps。\n";
		cout << "請輸入您的收入:";
	} 
    return 0;
}

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

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

struct fundrecord
{
	string Name;
	double Money;
};
int main()
{
	unsigned int num;
	int i,flag;
	cout << "'維護合法權利團體'資金記錄" << endl;
	cout << "捐獻者人數:";
	while (!(cin >> num))
	{
		cin.clear();
		cin.get();
		cout<<"請檢查輸入,它必須是一個正整數。\n";
		cout << "捐獻者人數:";
		
	}
	
	fundrecord *ps = new fundrecord[num];
	for(i =0;i<num;i++)
	{
		cout << "第" << i + 1 << "個捐獻者記錄:\n";
		cout << "姓名:";
		cin >> ps[i].Name;
		cout << "款項:";
		cin >> ps[i].Money;
	}
	flag = 0;
	cout << "\nGrand Patrons:" << endl;
	for(i=0;i<num;i++)
	{	
		if(ps[i].Money>10000)
		{
			flag++;
			cout << ps[i].Name << ",\t$" << ps[i].Money <<"\n\n";
		}
		
	}
	if (flag == 0)
			cout << "None\n\n";
	flag=0;
	cout << "Patrons:" << endl;
	for (i = 0; i<num; i++)
	{
		if (ps[i].Money<=10000)
		{
			flag++;
			cout << ps[i].Name << ",\t$" << ps[i].Money <<"\n\n";
		}
		
	}
	if (flag == 0)
			cout << "None\n\n" ;
	delete [] ps;
	system("pause");
    return 0;
}

6.7 編寫一個程式,它每次讀取一個單詞,直到使用者只輸入q。然後,該程式指出有多少個單詞以母音打頭,有多少個單詞以子音打頭,還有多少個單詞不屬於這兩類。為此,方法之一是,使用isalpha()來區分以字母和其他字元打頭的單詞,然後對於通過isalpha()測試的單詞,使用if或switch語句來確定哪些以母音打頭。

#include "stdafx.h"
#include <iostream>
#include<string>
using namespace std;

const int ArSize = 10;
bool isvowels(char);
int main()
{
	string word;
	char ch;
	int i = 0,j = 0, k = 0;//i個母音,j個子音,k個其他
	cout<<"Enter words (q to quit):\n";
	cin >> word;
	while (word != "q")
	{
			ch = word[0];
			if (!isalpha(ch))
				k++;
			else
				if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'||
					ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
					i++;
				else
					j++;
			cin >> word;
		
	} 
	cout << i << " words beginning with vowels.\n";
	cout << j << " words beginning with consonants.\n";
	cout << k << " others.\n";
	system("pause");
    return 0;
}

6.8 編寫一個程式,它開啟一個文字檔案,逐個字元地讀取該檔案,直到到達檔案末尾,然後指出該檔案中包含多少個字元。

我這裡還有一個沒有解決的問題:打不開絕對路徑的檔案。太奇怪了。

使用除錯模式的話,開啟的檔案1.txt要放在.vcxproj同一個資料夾下;使用exe執行的話,開啟的檔案1.txt要放在exe同一個資料夾下。

#include "stdafx.h"
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
	//char filename[SIZE];
	//ofstream outFile;
	//outFile.open("1.txt");
	ifstream inFile;
	//cout << "Enter name of data file: ";
	//cin.getline(filename, SIZE);
	inFile.open("1.txt");
	if (!inFile.is_open())
	{
		cout << "Could not open the file:"<<endl;//<< filename << endl;
		cout << "Program terminating.\n";
		system("pause");
		exit(EXIT_FAILURE);
	}
	
	char zifu;
	int count=0;//讀取有多少個字元
	inFile >> zifu;
	while (inFile.good())
	{
		++count;
		inFile >> zifu;
	}
	if (inFile.eof())
		cout << "End of file reached.\n";
	else if (inFile.fail())
		cout << "Input terminated by data mismatch.\n";
	else cout << "Input terminated by unknown reason.\n";
	if (count == 0)
		cout << "No data processed.\n";
	else
		cout << "檔案中有" << count << "個字元。\n";
	inFile.close();
	system("pause");
    return 0;
}

6.9  完成程式設計練習6,但從檔案中讀取所需的資訊。該檔案的第一項應為捐款人數,餘下的內容應為成對的行。在每一對中,第一行為捐款人姓名,第二行為捐款數額。即該檔案類似於下面:

4

Sam Stone

2000

Freida Flass

100500

Tammy Tubbs

5000

Rich Raptor

55000

// 66.cpp: 定義控制檯應用程式的入口點。
//
#include "stdafx.h"
#include <string>
#include<fstream>
#include <iostream>
using namespace std;

struct fundrecord
{
	string Name;
	double Money;
};
int main()
{
	//開啟檔案
	ifstream inFile;
	inFile.open("list.txt");
	if (!inFile.is_open())
	{
		cout << "Could not open the file:" << endl;
		cout << "Program terminating.\n";
		system("pause");
		exit(EXIT_FAILURE);
	}

	//處理資料
	unsigned int num;
	int i, flag;
	cout << "'維護合法權利團體'資金記錄" << endl;
	cout << "捐獻者人數:";
	inFile >> num;
	cout << num<<endl;
	fundrecord *ps = new fundrecord[num];
	inFile.get();//注意新增這一項接收回車\n
	for (i = 0; i<num; i++)
	{
		cout << "第" << i + 1 << "個捐獻者記錄:\n";
		cout << "姓名:";
		getline(inFile,ps[i].Name);
		cout << ps[i].Name<<"\t";
		cout << "款項:";
		inFile >> ps[i].Money;
		cout<< ps[i].Money<<endl;
		inFile.get();
			
	}
	flag = 0;
	cout << "\nGrand Patrons:" << endl;
	for (i = 0; i<num; i++)
	{
		if (ps[i].Money>10000)
		{
			flag++;
			cout << ps[i].Name << ",\t$" << ps[i].Money << "\n\n";
		}

	}
	if (flag == 0)
		cout << "None\n\n";
	flag = 0;
	cout << "Patrons:" << endl;
	for (i = 0; i<num; i++)
	{
		if (ps[i].Money <= 10000)
		{
			flag++;
			cout << ps[i].Name << ",\t$" << ps[i].Money << "\n\n";
		}

	}
	if (flag == 0)
		cout << "None\n\n";
	delete[] ps;	
	
	if (inFile.eof())
		cout << "End of file reached.\n";
	else if (inFile.fail())
		cout << "Input terminated by data mismatch.\n";
	else cout << "Input terminated by unknown reason.\n";
	inFile.close();

	system("pause");
	return 0;
}