7.1 C++為什麼要有自己的輸入輸出系統?
C++的編譯系統對資料類型進行嚴格的檢查,凡是類型不正確的資料都不可能通過編譯。
C++中需要定義眾多的使用者自訂類型且能夠輸入輸出。
7.2 C++有哪4個預定義的流對象?他們分別與什麼具體裝置相關聯?
標準輸入資料流對象cin、標準輸出資料流對象cout、非緩衝型的標準出錯流對象cerr和緩衝型的標準出錯流對象clog。
cin對應標準輸入裝置
cout對應標準輸出裝置
cerr對應標準錯誤輸出裝置
clog對應標準錯誤輸出裝置
7.3. cerr和clog間的區別是?
cerr不經過緩衝區直接顯示錯誤資訊。而clog存放在緩衝區,緩衝區滿或遇上endl時再輸出。
7.4 C++提供哪兩種控制輸入輸出格式的方法?
一種是使用ios類中的有關格式控制的流成員函數進行格式控制,另一種是使用稱為操縱符的特殊類型的函數控制。
7.5 C++進行檔案輸入輸出的基本過程是什嗎?
首先建立一個流對象,然後將這個流對象與檔案相關聯,即開啟檔案,此時才能進行讀寫操作,讀寫操作完成後再關閉這個檔案。
7.6-7.8 BCA
7.9
#include <iostream>#include <iomanip>using namespace std;int factorial(int n){ if(n == 0 || n == 1) return n; return factorial(n-1)*n;}int main(){ for(int i = 1; i <= 9; i++) { cout << setw(5) << factorial(i); if(i % 3 == 0) { cout << endl; } } return 0;}
7.10
#include <iostream>#include <iomanip>using namespace std;int main(){ for(int i = 1; i <= 7; i++) { cout << setw(16-i); for(int j = 1; j <= (2*i - 1); j++) { cout << 'A'; } cout << endl; } return 0;}
7.11
#include <iostream>#include <iomanip>using namespace std;class matrix{private: int data[2][3];public: matrix(){} friend ostream &operator<<(ostream &, matrix &); friend istream &operator>>(istream &, matrix &); friend matrix operator+(matrix &, matrix &);};ostream &operator<<(ostream &os, matrix &a){ for(int i = 0; i < 2; i++) { for(int j = 0; j < 3; j++) { os << a.data[i][j] << " "; } os << endl; } return os;}istream &operator>>(istream &in, matrix &a){ cout << "請輸入一個2行3列矩陣:" << endl; for(int i = 0; i < 2; i++) { for(int j = 0; j < 3; j++) { in >> a.data[i][j]; } } return in;}matrix operator+(matrix &a, matrix &b){ matrix temp; for(int i = 0; i < 2; i++) { for(int j = 0; j < 3; j++) { temp.data[i][j] = a.data[i][j] + b.data[i][j]; } } return temp;}int main(){ matrix m1, m2, total; cin >> m1 >> m2; total = m1 + m2; cout << total; return 0;}
7.12
#include <iostream>#include <fstream>using namespace std;int main(){ fstream fout("stock.txt",ios::out); if(!fout) { cout << "檔案開啟失敗!" << endl; return 1; } fout << "Shen fa zhan 000001\n"; fout << "shang hai qi che 600104\n"; fout << "Guang ju neng yuan 000096"; fout.close(); return 0;}
7.13
#include <iostream>#include <fstream>using namespace std;int main(){ char str[30]; fstream in("file1.txt", ios::in); if(!in) { cout << "開啟檔案file1.txt錯誤!\n"; abort(); } in >> str >> str; for(int i = 0; i < 30; i++) { if(str[i] != 0 && (str[i] < 'A')) { str[i] += ('A' - 'a'); } } fstream out("file2.txt", ios::out); if(!out) { cout << "開啟檔案file2.txt失敗!\n"; abort(); } out >> str; in.close(); out.close(); return 0;}
7.14
#include <iostream>#include <fstream>using namespace std;int main(){ char str[30]; fstream in("file1.txt", ios::in); if(!in) { cout << "開啟檔案file1.txt錯誤!\n"; abort(); } in >> str >> str; for(int i = 0; i < 30; i++) { if(str[i] != 0 && (str[i] < 'A')) { str[i] += ('A' - 'a'); } } fstream out("file2.txt", ios::app); if(!out) { cout << "開啟檔案file2.txt失敗!\n"; abort(); } out >> str; in.close(); out.close(); return 0;}
7.15 不會。