Download presentation
Presentation is loading. Please wait.
1
計算機概論實習 2007-06-08
2
2 Review of Practice 8 (P8) PLEASE write a program that when you fail to open a file, you have to throw a exception. Directly using try, catch, and throw Define a openfile() function that will throw exception when this function occurs "can not open a file"
3
3 A Sample Code #include #include // exit prototype #include using namespace std; void openfile(ifstream &inClientFile, char* filename){ inClientFile.open( filename, ios::in ); if ( !inClientFile ) { throw "File could not be opened"; }
4
4 void main(){ ifstream inClientFile; char filename[80]; cin >> filename; try{ openfile(inClientFile, filename); } catch(const char* e){ cout << e; exit(1); } char cont[30]; while ( inClientFile >> cont ) cout << cont << endl; inClientFile.close(); }
5
5 Some Notations!!! (1/2) void openfile(ifstream &inClientFile, string filename){ inClientFile.open( filename, ios::in ); if ( !inClientFile ) { throw "File could not be opened"; } void main(){ ifstream inClientFile; string filename; cin >> filename; try{ openfile(inClientFile, filename); } : } Error!! 無法將參數 1 從 'std::string' 轉換成 'const char *' 改成 filename.data()
6
6 Some Notations!!! (2/2) void openfile(ifstream &inClientFile, char* filename){ inClientFile.open( filename, ios::in ); if ( !inClientFile ) { throw "File could not be opened"; } void main(){ : catch(string e){ cout << e; exit(1); } : } Compile is OK, but… 改成 string("File could not be opened");
7
7 Try it!!! Please write a problem that ask user to input a integer number Please use try, catch, throw way to design a function for checking if the input is a integer. Please ask user to re-input if the input is incorrect.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.