




已阅读5页,还剩30页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
SavitchInstructors Resource GuideProblem Solving w/ C+, 7eChapter 16Chapter 16Exception Handling1. Solutions to and Remarks on Selected Programming Problems1 TimeWrite a program to covnert from 24-hour time to 12-hour time. Remarks:The text gives sample dialog. The code I give produces a slightly different dialog that diagnoses particular input errors by providing an appropriate message to the exception object at the point the error is detected and the exception is thrown. This solution is only slightly more complex than a solution that gives the requested dialog.I used the class DigtalTime from Chapter 11 as a starting point. I removed functions not needed, and replaced the terminating error reporting code with calls to the required exception, TimeFormatError. I provided error messages appropriate to the particular errors as detected. I then inserted the try-catch blocks, terminating the program at the error. After this was running, I provided the loop, to request repetition. Bug (perhaps a quirk?): If an input error causes an exception to be thrown, the code diagnoses the error, then immediately requests another 24 hour time for converstion without requesting approval from the user./ dtime.h/ Taken from Chapter 11/ This is the HEADER FILE dtime.h. This is a reduction of /the INTERFACE for the class DigitalTime from Chapter 11 for /Chapter 16 Programming Problem 1. The operator= and /Advance members are not needed so I deleted them. I have /added the required exception class TimeFormatMistake./ Values of this type are times of day. The values are /input and output in 24 hour notation as in 9:30 for 9:30 /AM and 14:45 for 2:45 PM.#ifndef DTIME_H#define DTIME_H#include #include using namespace std;class TimeFormatMistake public: TimeFormatMistake(std:string mesg) throw () message = mesg; string what() throw() return message; private: std:string message;class DigitalTimepublic: DigitalTime(int the_hour, int the_minute) throw(TimeFormatMistake); /Precondition: 0 = the_hour = 23 and /0 = the_minute (std:istream& ins, DigitalTime& the_object)throw(TimeFormatMistake); /Overloads the operator for input values of type /DigitalTime. /Precondition: If ins is a file input stream, then ins has /already been connected to a file. friend std:ostream& operator (std:ostream& outs, const DigitalTime& the_object); /Overloads the operator for output values of type / DigitalTime. /Precondition: If outs is a file output stream, then outs /has already been connected to a file. void Print12HourTime() throw();private: int hour; int minute;#endif /DTIME_H/ file: dtime.cpp/ Adapted from Chapter 11./This is the IMPLEMENTATION FILE for Programming Problem #1./Theoriginal dtime.cxx has been modified to add throw /declarations,replace error message reporting and exit code /with exception throw statements./I have removed definitions of members not used in this /problem. The interface for the class DigitalTime is in the /header file dtime.h.#include #include #include #include dtime.husing namespace std;/These PROTOTYPES are for the definition of the overloaded /input operator :void read_hour(istream& ins, int& the_hour) throw (TimeFormatMistake);/Precondition: Next input in the stream ins is a time in /notation, like 9:45 or 14:45./Postcondition: the_hour has been set to the hour part of /the time. The colon has been discarded and the next input /to be read is the minute.void read_minute(istream& ins, int& the_minute);/Reads the minute from the stream ins after read_hour has /read the digit_to_int(char c) throw (TimeFormatMistake)/Precondition: c is one of the digits 0 through 9./ Returns the integer for the digit; e.g., / digit_to_int(3) returns 3. if ( 0 = c & c = 9) return c - 0; throw TimeFormatMistake(non digit arg for digit_to_int); / return 0; / ANSI requires a return statement, even if inaccessible./Uses iostream, cstdlib and stdexcept:DigitalTime:DigitalTime(int the_hour, int the_minute) throw (TimeFormatMistake) if (the_hour 23 | the_minute 59) throw TimeFormatMistake ( Illegal argument to DigitalTime constructor.); else hour = the_hour; minute = the_minute; DigitalTime:DigitalTime( ) throw() hour = 0; minute = 0;void DigitalTime:Print12HourTime() throw() enum AM, PM am_pm = PM; int h, m; if (hour 12) am_pm = AM; if (hour = 0 | hour = 12) h = 12; else if(hour 12) h = hour; else h = hour - 12; cout h : ; if (0 = minute & minute 10) cout 0 minute; else cout minute; if(am_pm = AM) cout AM; else cout (istream& ins, DigitalTime& the_object) throw (TimeFormatMistake) read_hour(ins, the_object.hour); read_minute(ins, the_object.minute); return ins;/Uses iostream:ostream& operator (ostream& outs, const DigitalTime& the_object) outs the_object.hour :; if (the_object.minute 10) outs 0; outs c1 c2; if (!( isdigit(c1) & (isdigit(c2) | c2 = :) throw TimeFormatMistake( Non-digit input to read_hour or bad separatorn); if (isdigit(c1) & c2 = :) the_hour = digit_to_int(c1); else /(isdigit(c1) & isdigit(c2) the_hour = digit_to_int(c1)*10 + digit_to_int(c2); ins c2; /discard : if (c2 != :) throw TimeFormatMistake( Error illegal separating charactern); if ( the_hour 23 ) throw TimeFormatMistake( Error illegal range for input to read_hourn);/Uses iostream, cctype, stdlib and stdexcept:void read_minute(istream& ins, int& the_minute) char c1, c2; ins c1 c2; if (!(isdigit(c1) & isdigit(c2) throw TimeFormatMistake(Non-digit input to read_minuten); the_minute = digit_to_int(c1)*10 + digit_to_int(c2); if (the_minute 59) throw TimeFormatMistake( Error illegal range for input to read_minuten);/ Ch16Prog01.cxx/ driver program for Chapter 16 Programming Problem 1.#include dtime.hchar getAns() char c; cin.get(c); while (c != y& c != n) cout y/n, please.n; cin.get(c); return c;int main() using namespace std; DigitalTime time24; char stuff1002; char ans; while( true ) cout time24; cout That is the same time asn; time24.Print12HourTime(); cout endl; cout Again? (y/n) n; ans = getAns(); if (ans = n) return 0; catch (TimeFormatMistake tfm) cout tfm.what() flush; cin.getline(stuff, 1000); / discard all waiting input return 0;Trial RunEnter time in 24 hour format: hh:mm13:07That is the same time as1:07 PMAgain? (y/n) y/n, please.yEnter time in 24 hour format: hh:mm10:15That is the same time as10:15 AMAgain? (y/n) y/n, please.yEnter time in 24 hour format: hh:mm10:65Error illegal range for input to read_minuteEnter time in 24 hour format: hh:mm16:05That is the same time as4:05 PMAgain? (y/n) y/n, please.nbash-2.03$ */2. No Solution Provided.3./ */ Ch16Proj3.cpp/ This program draws a histogram using input values from 1-10./ It catches any input that is not a numeric value in the/ proper range./ *#include #include using namespace std;/ Exception classesclass OutOfRange;class NonDigits;/ Function Prototypesbool isAllDigits(const string s);/ =/ isAllDigits:/ Returns true if the input string/ contains only digits./ =bool isAllDigits(const string s)int i;for (i=0; is.length(); i+)char c = si;if (!isdigit(c) return false;return true;/ =/ main function/ =const int MAX = 10;int main() int histogramMAX; int i, num, temp; string s; / Initialize histogram to all zero values for (i=0; iMAX; i+) histogrami = 0; cout Each number must be from 1-10. How many numbers to enter? num; i = 0; while (i num) / Input each number, throwing two possible exceptions based on / error conditions try cout Enter number (i+1) : s; if (!isAllDigits(s) throw NonDigits(); temp = atoi(s.c_str();/ Convert string to an integer if (temp10) throw OutOfRange(); histogramtemp-1+; i+; catch (NonDigits e) cout Please enter your text using digits only. Try again.n; catch (OutOfRange e) cout The number must be between 1 and 10. Try again. endl; / Show histogram cout endl Here is the histogram: endl; for (i=0; i MAX; i+) cout (i+1) : ;for (int j=0; jhistogrami; j+)cout *;cout endl; return 0;4-6. No Solutions Provided.7./ */ Ch16Proj7.cpp/ Programming Project 7 in Chapter 9 described a technique to emulate a/ 2D array with wrapper functions around a 1D array. If the indices of/ a desired entry in the 2D array were invalid (e.g., out of range) you/ were asked to print an error message and exit the program. Modify/ this program (or do it for the first time) to instead throw an/ ArrayOutOfRangeError exception if either the row or column indices are/ invalid. Your program should define the ArrayOutOfRangeError/ exception class. / */ File Name: twodimensional.cpp/ Author: / Email Address:/ Project Number: 16.07/ Description: Functions that emulate a 2-dimensional array using a /1-dimensional array. This version throws an exception/when an invalid row or column index is used./ Last Changed: October 14, 2007#include #include using namespace std;/ Exception classclass ArrayOutOfRangeErrorpublic: ArrayOutOfRangeError(); / Constructs an exception with no message ArrayOutOfRangeError(string msg, int rows, int cols, int desired_row, int desired_col); / Constructs an exception with the given message and row/column / data string get_message(); / Returns the exceptions message string int get_rows(); / Returns the number of rows in the array int get_columns(); / Returns the number of columnsin the array int get_desired_row(); / Returns the requested row number int get_desired_column(); / Returns the requested column number void write_error(); / Writes the error message to coutprivate: string message; int rows; int cols; int desired_row; int desired_col;/ Creates an emulated two-dimensional array with the given number of/ rows and * create2DArray(int rows, int columns);/ Stores val in the desired position in an emulated two-dimensional arrayvoid set(int *arr, int rows, int columns, int desired_row, int desired_column, int val) throw (ArrayOutOfRangeError);/ Retrieves the value in the desired position in an emulated / two-dimensional arrayint get(int *arr, int rows, int columns, int desired_row, int desired_column)throw (ArrayOutOfRangeError);/ Helper function for testing range-checkingvoid test_exception(string msg, int *arr, int rows, int columns, int desired_row, int desired_column, int val);int main() const int ROWS = 13; const int COLS = 7; int count = 0; / Create a 2D array int *table = create2DArray(ROWS, COLS); / Populate it for (int r = 0; r ROWS; r+) for (int c = 0; c COLS; c+) set(table, ROWS, COLS, r, c, count+); / Print the arrays contents cout Array contents: endl endl; for (int r = 0; r ROWS; r+) for (int c = 0; c COLS; c+) int val = get(table, ROWS, COLS, r, c); cout.width(4); cout val;cout endl; / Try some boundary cases test_exception(Column too large., table, ROWS, COLS, 0, COLS, 400); test_exception(Row too large., table, ROWS, COLS, ROWS, 0, 400); test_exception(Row and column too large., table, ROWS, COLS, ROWS, COLS, 400); test_exception(Column too small., table, ROWS, COLS, 0, -1, 400); test_exception(Row too small., table, ROWS, COLS, -1, 0, 400); test_exception(Row and column too small., table, ROWS, COLS, -1, -1, 400); return 0;/ Helper function for testing range-checkingvoid test_exception(string msg, int *table, int rows, int cols, int desired_row, int desired_col, int val) cout endl msg endl; try cout Testing set(.): ; set(table, rows, cols, desired_row, desired_col, val); catch(ArrayOutOfRangeError e) e.write_error(); try cout Testing get(.): ; int val = get(table, rows, cols, desired_row, desired_col); catch(ArrayOutOfRangeError e) e.write_error(); / Creates an emulated two-dimensional array with the given number of/ rows and * create2DArray(int rows, int columns) return new introws * columns;/ Utility method that checks desired row/column arguments for validity,/ returning an explanation in the message string if something is/ wrong.bool check_args(int rows, int columns, int desired_row, int desired_column, string& message) bool ok = false; if (desired_row 0) message = desired_row cannot be less than 0; else if (desired_column = rows) message = desired_row must be less than row count; else if (desired_column = columns) message = desired_column must be less than column count; else ok = true; return ok;/ Stores val in the desired position in an emulated two-dimensional arrayvoid set(int *arr, int rows, int columns, int desired_row, int desired_column, int val) throw (ArrayOutOfRangeError) string msg; if (check_args(rows, columns, desired_row, desired_column, msg) arrdesired_row * columns + desired_column = val; else throw ArrayOutOfRangeError( msg, rows, columns, desired_row, desired_column); / Retrieves the value in the desired position in an emulated / two-dimensional arrayint get(int *arr, int rows, int columns, int desired_row, int desired_column) throw (ArrayOutOfRangeError) int result; string msg; if (check_args(rows, columns, desired_row, desired_column, msg) result = arrdesired_row * columns + desired_column; else throw ArrayOutOfRangeError( msg, rows, columns, desired_row, desired_column); return result;/ Constructs an exception with no messageArrayOutOfRangeError:ArrayOutOfRangeError() : message(), rows(0), cols(0), desired_row(0), desired_col(0)/ Constructs an exception with the given messageArrayOutOfRangeError:ArrayOutOfRangeError( string msg, int r, int c, int d_row, int d_col) : message(msg), rows(r), cols(c), desired_row(d_row), desired_col(d_col)/ Returns the exceptions message stringstring ArrayOutOfRangeError:get_message() return message;/ Returns the number of rows in the arrayint ArrayOutOfRangeError:get_rows() return rows;/ Returns the number of columns in the arrayint ArrayOutOfRangeError:get_columns() return cols;/ Returns the requested row numberint ArrayOutOfRangeError:get_desired_row() return desired_row;/ Returns the requested column numberint ArrayOutOfRangeError:get_desired_column() return desired_col;/ Writes the error message to coutvoid ArrayOutOfRangeError:write_error() cout message (rows= rows , cols= cols , desired_row= desired_row , desired_col= desired_col ) endl;2. Outline of Topics in the Chapter16.1 Exception-Handling BasicsA Toy Example of Exception HandlingDefininin
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 钢桥内防腐翻新施工方案
- 草地灌溉维修方案范本
- 湖北不锈钢风管施工方案
- 枇杷种植规划方案范本
- 化学危废库施工方案
- 诉讼审计方案范本
- 2025年江苏省绿化苗木供需合同
- 易货公司运行方案范本
- 兰州中考体育题库及答案
- 装不锈钢门安全施工方案
- 2025年中国建设银行个人信用贷款合同
- 2024-2025学年人教版8年级数学上册《 整式的乘法与因式分解》单元测试试题(详解版)
- 2025年全国网约车试题及答案
- 卫生系统信息安全培训课件
- 文物建筑勘查设计取费标准(2020年版)
- 2025年成考专升本《生态学基础》试题与答案
- 工厂出差安全培训内容记录课件
- 河南省新未来2026届高三上学期9月联合测评政治试卷(含答案)
- 危重孕产妇救治中心评估报告
- 风电项目工程验收规范标准
- 职业人群心理健康知识讲座
评论
0/150
提交评论