1. 程式人生 > >c++ premier Plus書--C++列舉和switch, cin/cout讀/寫檔案

c++ premier Plus書--C++列舉和switch, cin/cout讀/寫檔案

C++中switch和列舉結合使用:

#include "iostream"
using namespace std;

// 建立一個列舉型別常量, 實際對應的是0~2
enum {red, orange, yellow};

int main() {
	cout << "Enter color code (0~2)";
	int code;
	cin >> code;
	while (code >= red && code <= yellow)
	{
		switch(code)
		{
			case red : 
				cout << "red" << endl;
				break;
			case orange:
				cout << "orange" << endl;
				break;
			case yellow:
				cout << "yellow" << endl;
				break;	
			default :
				cout << "unkonw" << endl;
		}
		cout << "Enter color code (0~2)";
		cin >> code;
	}
	cout << "end" << endl;
	return 0;
}

輸出結果:

注意c++中switch語句只能對整數值進行處理(java 高版本可以對string進行處理), 而列舉實際也是int型變數, switch將int和列舉進行比較的時候, 會將列舉提升為int, 所以列舉也可進行處理. 

 

再看一個while迴圈的簡單使用

注意while條件判斷中的語句寫法

#include "iostream"
using namespace std;

const int MAX = 5;

int main() {
	int golf[MAX];
	cout << "Please enter your golf scores." << endl;
	cout << "you must enter " << MAX << " rounds." << endl;
	
	int i;
	for (i = 0; i < MAX; i++) 
	{
		cout << "round #" << i + 1 << ": " << endl;
		// 如果使用者輸入的不是int型數值
		// cin >> golf[i] 這個表示式由於是放在判斷語句中
		// 會返回false
		while (!(cin >> golf[i]))
		{
			// 首先清空cin的輸入
			cin.clear();
			// 捨棄掉使用者錯誤的輸入
			// 通過判斷是不是到了輸入的末尾判斷
			while(cin.get() != '\n') 
				// 通過continue來捨棄輸入
				continue;
			cout << "please enter a number : ";
		}
	}
	double total = 0;
	for (int i = 0; i < MAX; i++)
	{
		total += golf[i];
	}
	cout << total / MAX  << " = average score " 
		<< MAX << " rounds" << endl;

	return 0;
}

執行結果

關於程式需要注意的地方, 註釋寫的比較明白

 

cin/cout讀寫檔案 

寫檔案:

簡單IO

宣告一個ofstream物件, 並將其通檔案關聯起來後, 就可以像使用cout那樣使用它, 所有可用於cout的操作和方法(例如 << , endl, setf()) 都可用於ofstreawm物件.

使用檔案輸出的主要步驟如下:

1.包含標頭檔案fstream

2.建立一個ofstream物件

3.將該ofstream物件同一個檔案關聯起來

4.像使用cout那樣使用該ofstream物件

看一個例子:

// 向檔案中輸出內容
#include "iostream"
#include "fstream"
using namespace std;

int main()
{
	char automobile[50];
	int year;
	double a_price;
	double d_price;
	
	// 建立一個ofstrem物件
	ofstream outFile;
	// 和一個檔案關聯起來
	outFile.open("carinfo.txt");
	
	cout << "Enter the make and model of automobile: ";
	// 接收一行輸入, 最長50個字元, 包含\0
	cin.getline(automobile, 50);
	cout  << "Enter the model year: ";
	cin >> year;
	cout << "Enter the original asking price: ";
	cin >> a_price;
	d_price = 0.9 * a_price;
	
	// 表示輸出浮點數的時候, 使用一般方式而不是科學計數法
	cout << fixed;
	// 顯示幾位有效數字, 如果和上面的配合使用, 就表示
	// 顯示小數點後幾位有效數字
	cout.precision(2);
	// 強制顯示浮點數, 小數點後的0
	cout.setf(ios_base::showpoint);
	cout << "Make and model : " << automobile << endl;
	cout << "Year: " << year << endl;
	cout << "Was asking $" << a_price << endl;
	cout << "Now asking $" << d_price << endl;
	
	outFile << fixed;
	outFile.precision(4);
	outFile.setf(ios_base::showpoint);
	outFile << "Make and model : " << automobile << endl;
	outFile << "Year: " << year << endl;
	outFile << "Was asking $" << a_price << endl;
	outFile << "Now asking $" << d_price << endl;
	// 關閉輸出流
	outFile.close();
	
	return 0;
}

看程式輸出結果

注意事項:

1.outFile.close() 關閉輸出流, 表示用完該檔案後將其關閉, 不呼叫的話在程式正常終止的時候也會關閉

2.outFile.open("carinfo.txt"); 這條語句會在當前目錄下 如果檔案不存在建立一個該名稱的txt檔案, 如果檔案存在那麼會將檔案清空

其餘的注意事項都在註釋裡寫明白了

 

 

接下來看cin從檔案中讀入資料

// 從檔案中讀入
#include "iostream"
#include "fstream"
#include "cstdlib" // support for exit()

const int SIZE = 60;
using namespace std;

int main()
{
	
	char filename[SIZE];
	// 宣告一個file input stream
	ifstream inFile;
	cout << "Enter name of data file : ";
	cin.getline(filename, SIZE);
	// 將inFile和一個檔案關聯起來
	inFile.open(filename);
	// 判斷是否能開啟檔案
	if (!inFile.is_open())
	{
		cout << "Could not open the file " << filename << endl;
		cout << "Program terminating. \n";
		exit(EXIT_FAILURE);
	}
	
	double value;
	double sum = 0.0;
	int count;
	
	// 獲取第一個value
	inFile >> value;
	// 判斷是否是正確的數值, 並且不能是結尾符EOF
	while (inFile.good())
	{
		++count;
		sum += value;
		inFile >> value;
	}
	if (inFile.eof())
		cout << "End of file reached." << endl;
	else if(inFile.fail())
		cout << "Input terminated by data mismatch." << endl;
	else
		cout << "Input terminated for unknow reason.\n" << endl;
	
	if (count == 0)
		cout << "No data processed." << endl;
	else {
		cout << "Items read : " << count << endl;
		cout << "Sum: " << sum << endl;
		cout << "Average : " << sum / count << endl;
	}
	// 記得關閉輸入流
	inFile.close();
	return 0;
}

 看一下輸出結果:

其實和cout像檔案中輸出內容類似, 只不過使用的類和方法不同而已