611 18200 計算機程式語言 Lecture 09-1 國立臺灣大學生物機電系 9 9 Completing the Basics.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

CS 6301 Lecture 2: First Program1. CS Topics of this lecture Introduce first program  Explore inputs and outputs of a program Arithmetic using.
Chapter 10.
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
Chapter 5: Loops and Files.
Chapter 15.
Chapter 2: Introduction to C++.
Chapter 8: I/O Streams and Data Files. In this chapter, you will learn about: – I/O file stream objects and functions – Reading and writing character-based.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
計算機程式語言 Lecture 8-1 國立臺灣大學生物機電系 8 8 I/O File Streams and Data Files.
Introduction to C++ Programming
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
In Addition... To the string class from the standard library accessed by #include C++ also has another library of string functions for C strings that can.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 3: Requirements Specification, C++ Basics.
1 Chapter 4 Program Input and the Software Design Process.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
計算機程式語言 Lecture 13-1 國立臺灣大學生物機電系 13 Structures.
計算機程式語言 Lecture 03-1 國立臺灣大學生物機電系 3 3 Assignment, Formatting, and Interactive Input.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 9 I/O Streams and Data Files
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
C++ How to Program, Late Objects Version, 7/e © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
TEXT FILES. CIN / COUT REVIEW  We are able to read data from the same line or multiple lines during successive calls.  Remember that the extraction.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
1 Character Strings (Cstrings) Reference: CS215 textbook pages
Loops and Files. 5.1 The Increment and Decrement Operators.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
計算機程式語言 Lecture 02-1 國立台灣大學生物機電系 林達德 2 2 Introduction to C++ Programming.
Chapter 15 Strings as Character Arrays
Chapter 9: Completing the Basics. In this chapter, you will learn about: – Exception handling – Exceptions and file checking – The string class – Character.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
計算機程式語言 Lecture 03-1 國立台灣大學生物機電系 林達德 3 3 Introduction to Classes and Objects.
An Introduction to Programming with C++ Sixth Edition Chapter 13 Strings.
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Chapter 4 Strings and Screen I/O. Objectives Define strings and literals. Explain classes and objects. Use the string class to store strings. Perform.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
STRUCTURED PROGRAMMING Complete C++ Program. Content 2  Main Function  Preprocessor directives  User comments  Escape characters  cout statement.
Chapter 2 of C++ How to Program, 10/e © by Pearson Education, Inc. All Rights Reserved.
© by Pearson Education, Inc. All Rights Reserved.
Topic Pre-processor cout To output a message.
Chapter 2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
A First Book of ANSI C Fourth Edition
Chapter 2 part #3 C++ Input / Output
C++ fundamentals Lecture 1, Chapter 2 – pp /22/2018 Y K Choi.
2.1 Parts of a C++ Program.
Introduction to C++ Programming
Introduction to C++ Programming
Chapter 2: Introduction to C++.
Chapter 2 part #3 C++ Input / Output
Chapter 1 c++ structure C++ Input / Output
Presentation transcript:

計算機程式語言 Lecture 09-1 國立臺灣大學生物機電系 9 9 Completing the Basics

計算機程式語言 Lecture 09-2 國立臺灣大學生物機電系 Contents Exception handling Exceptions and file checking The string Class Character manipulation functions Input data validation Namespaces and creating a personal library Common programming errors

計算機程式語言 Lecture 09-3 國立臺灣大學生物機電系 Exception Handling Traditional C++ approach to error handling uses a function to return a specific value to indicate specific operations Latest C++ compilers have added a technique designed for error detection and handling referred to as exception handling When an error occurs while a function is executing, an exception is created An exception is a value, a variable, or an object containing information about the error at the point the error occurs

計算機程式語言 Lecture 09-4 國立臺灣大學生物機電系 Exception Handling Throwing an exception: Process of generating an exception is referred to as In general two fundamental types of errors can cause C++ exceptions –Those resulting from inability to obtain a required resource, over which the programmer has no control –Errors than can be checked and handled, over which the programmer has control

計算機程式語言 Lecture 09-5 國立臺灣大學生物機電系 Figure 9.1 Exception-Handling Terminology Exception Handling

計算機程式語言 Lecture 09-6 國立臺灣大學生物機電系 Exception Handling The general syntax of the code required to throw and catch an exception is: try { // one or more statements, // at least one of which should // be capable of throwing an exception; } catch(exceptionDataType parameterName) { // one or more statements }

計算機程式語言 Lecture 09-7 國立臺灣大學生物機電系 Exception Handling Program 9.1 #include using namespace std; int main() { int numerator, denominator; try { cout << "Enter the numerator (whole number only): "; cin >> numerator; cout << "Enter the denominator(whole number only): "; cin >> denominator; if (denominator == 0) throw denominator; // an integer value is thrown else cout << numerator <<'/' << denominator << " = " << double(numerator)/ double(denominator) << endl; } catch(int e) { cout << "A denominator value of " << e << " is invalid." << endl; exit (1); } return 0; }

計算機程式語言 Lecture 09-8 國立臺灣大學生物機電系 Exceptions and File Checking Error detection and exception handling are used in C++ programs that access one or more files General exception handling code (section 9.2) try { // one or more statements, at least one // of which should throw an exception } catch(exceptionDataType parameterName) { // one or more statements } Program 9.3 illustrates file opening exception handling

計算機程式語言 Lecture 09-9 國立臺灣大學生物機電系 Opening Multiple Files Example: Read the data from character-based file named info.txt, one character at a time, and write this data to file named info.bak –Essentially, this is a file-copy program Figure 9.2 illustrates structure of streams needed to produce file copy Program 9.5 creates info.bak file as an exact duplicate of info.txt file using procedure described in Figure 9.2

計算機程式語言 Lecture 國立臺灣大學生物機電系 Opening Multiple Files Figure 9.2 The file copy stream structure Program Operating System Interface info.txt backup.txt Read Write ComputerDisk

計算機程式語言 Lecture 國立臺灣大學生物機電系 Opening Multiple Files Program 9.5 #include #include // needed for exit() #include using namespace std; int main() { string fileOne = "info.txt"; // put the filename up front string fileTwo = "info.bak"; char ch; ifstream inFile; ofstream outFile; try //this block tries to open the input file { // open a basic input stream inFile.open(fileOne.c_str()); if (inFile.fail()) throw fileOne; } // end of outer try block catch (string in) // catch for outer try block { cout << "The input file " << in << " was not successfully opened." << endl << " No backup was made." << endl; exit(1); }

計算機程式語言 Lecture 國立臺灣大學生物機電系 Opening Multiple Files Program 9.5 (Continued) try // this block tries to open the output file and { // perform all file processing outFile.open(fileTwo.c_str()); if (outFile.fail())throw fileTwo; while ((ch = inFile.get())!= EOF) outFile.put(ch);; inFile.close(); outFile.close(); } catch (string out) // catch for inner try block { cout << "The backup file " << out << " was not successfully opened." << endl; exit(1); } cout << "A successful backup of " << fileOne << " named " << fileTwo << " was successfully made." << endl; return 0; }

計算機程式語言 Lecture 國立臺灣大學生物機電系 The string Class Provides methods for declaring, creating and initializing a string String literal: any sequence of characters enclosed in double quotation marks Examples: –“This is a string” –“Hello World!” Double quotation marks identify the beginning and end of a string –Quotation marks not stored with string

計算機程式語言 Lecture 國立臺灣大學生物機電系 The string Class Hello Character position: Figure 9.3 The storage of a string as a sequence of characters

計算機程式語言 Lecture 國立臺灣大學生物機電系 string Class Functions Table 9.2 string Class Constructors (Required Header File Is string )

計算機程式語言 Lecture 國立臺灣大學生物機電系 string Class Functions

計算機程式語言 Lecture 國立臺灣大學生物機電系 string Class Functions

計算機程式語言 Lecture 國立臺灣大學生物機電系 Program 9.6 #include using namespace std; int main() { string str1; // an empty string string str2("Good Morning"); string str3 = "Hot Dog"; string str4(str3); string str5(str4, 4); string str6 = "linear"; string str7(str6, 3, 3); cout << "str1 is: " << str1 << endl; cout << "str2 is: " << str2 << endl; cout << "str3 is: " << str3 << endl; cout << "str4 is: " << str4 << endl; cout << "str5 is: " << str5 << endl; cout << "str6 is: " << str6 << endl; cout << "str7 is: " << str7 << endl; return 0; } string Class Functions

計算機程式語言 Lecture 國立臺灣大學生物機電系 The Output from Program 9.6 str1 is: str2 is: Good Morning str3 is: Hot Dog str4 is: Hot Dog str5 is: Dog str6 is: linear str7 is: ear string Class Functions

計算機程式語言 Lecture 國立臺灣大學生物機電系 string Input and Output In addition to methods listed in Table 9.2, strings can be: –Input from the keyboard –Displayed on the screen Additional methods include: –cout : General purpose screen output –cin : General purpose terminal input that stops reading when a whitespace is encountered

計算機程式語言 Lecture 國立臺灣大學生物機電系 Table 9.3 string Class Input and Output string Input and Output

計算機程式語言 Lecture 國立臺灣大學生物機電系 string Input and Output Additional methods include: –getline(cin, strObj) : General purpose terminal input that inputs all characters entered into the string named strObj and stops accepting characters when it receives a newline character ( \n ) –Example: getline(cin, message) Continuously accepts and stores characters entered at terminal until Enter key is pressed. –Pressing Enter key generates newline character, ‘\n’ –All characters except newline stored in string named message

計算機程式語言 Lecture 國立臺灣大學生物機電系 Figure 9.5 Inputting a string with getline() getline() characters \ncharacters string Input and Output

計算機程式語言 Lecture 國立臺灣大學生物機電系 string Input and Output Program 9.7 #include using namespace std; int main() { string message; // declare a string object cout << "Enter a string:\n"; getline(cin, message); cout << "The string just entered is:\n" << message << endl; return 0; }

計算機程式語言 Lecture 國立臺灣大學生物機電系 string Input and Output Sample run of Program 9.7: Enter a string: This is a test input of a string of characters. The string just entered is: This is a test input of a string of characters.

計算機程式語言 Lecture 國立臺灣大學生物機電系 string Input and Output In Program 9.7, the cin object cannot be used in place of getline() cin reads a set of characters up to a blank space or a newline character Statement cin >> message cannot be used to enter the characters This is a string –Statement results in word This assigned to message cin ’s usefulness for entering string data limited - blank space terminates cin extraction

計算機程式語言 Lecture 國立臺灣大學生物機電系 string Input and Output General form of getline() method: getline(cin, strObj, terminatingChar) –strObj : a string variable name –terminatingChar : an optional character constant or variable specifying the terminating character Example: –getline(cin, message, ‘!’) Accepts all characters entered at the keyboard, including newline, until an exclamation point is entered

計算機程式語言 Lecture 國立臺灣大學生物機電系 Caution: The Phantom Newline Character Unexpected results occur when: –cin input stream and getline() method are used together to accept data –Or when cin input stream is used to accept individual characters Example: Program 9.8 –When value is entered and Enter key is pressed, cin accepts value but leaves the ‘\n’ in the buffer –getline() picks up the code for the Enter key as the next character and terminates further input

計算機程式語言 Lecture 國立臺灣大學生物機電系 Caution: The Phantom Newline Character Program 9.8 #include using namespace std; int main() { int value; string message; cout << "Enter a number: "; cin >> value; cout << "The number entered is:\n" << value << endl; cout << "Enter text:\n"; getline(cin, message); cout << "The string entered is:\n" << message << endl; return 0; }

計算機程式語言 Lecture 國立臺灣大學生物機電系 Caution: The Phantom Newline Character Sample run of Program 9.8: Enter a number: 26 The number entered is 26 Enter text: The string entered is

計算機程式語言 Lecture 國立臺灣大學生物機電系 Caution: The Phantom Newline Character Solutions to the “phantom” Enter key problem –Do not mix cin with getline() inputs in the same program –Follow the cin input with the call to cin.ignore() –Accept the Enter key into a character variable and then ignore it Preferred solution is the first option

計算機程式語言 Lecture 國立臺灣大學生物機電系 Figure 9.6 Typed characters are first stored in a buffer Caution: The Phantom Newline Character

計算機程式語言 Lecture 國立臺灣大學生物機電系 String Processing Methods for manipulating strings (Table 9.4): –Most commonly used string class method is length() which returns the number of characters in the string Most commonly used methods: –Accessor –Mutator –Additional methods that use standard arithmetic and comparison operators

計算機程式語言 Lecture 國立臺灣大學生物機電系 String Processing Program 9.10 #include using namespace std; int main() { string str = "Counting the number of vowels"; int i, numChars; int vowelCount = 0; cout << "The string: \"" << str "\"" << endl; numChars = str.length(); for (i = 0; i < numChars; i++) { switch(str.at(i)) // here is where a character is retrieved { case 'a': case 'e': case 'i': case 'o': case 'u': vowelCount++; } cout << " contains " << vowelCount << " vowels." << endl; return 0; }

計算機程式語言 Lecture 國立臺灣大學生物機電系 String Processing String expressions may be compared for equality using standard relational operators String characters stored in binary using ASCII or Unicode code as follows: –A blank precedes (is less than) all letters and numbers –Letters are stored in order from A to Z –Digits stored in order from 0 to 9 –Digits come before uppercase characters, which are followed by lowercase characters

計算機程式語言 Lecture 國立臺灣大學生物機電系 String Processing Procedure for comparing strings: –Individual characters compared a pair at a time If no differences, the strings are equal Otherwise, the string with the first lower character is considered the smaller string Examples: –"Hello" is greater than "Good Bye " because the first H in Hello is greater than the first G in Good Bye –"Hello" is less than "hello" because the first H in Hello is less than the first h in hello

計算機程式語言 Lecture 國立臺灣大學生物機電系 Figure 9.8 Initial storage of a string object Figure 9.9 The string after the insertion String Processing string str = “This cannot be” str.insert(4, “ I know”);

計算機程式語言 Lecture 國立臺灣大學生物機電系 Figure 9.10 The string after the replacement String Processing str.replace(12, 6, “to”);

計算機程式語言 Lecture 國立臺灣大學生物機電系 Figure 9.11 The string after the append String Processing str = str + “ correct”

計算機程式語言 Lecture 國立臺灣大學生物機電系 Character Manipulation Methods C++ language provides a variety of character class functions (listed in Table 9.5) Function declarations (prototypes) for these functions are contained in header files string and cctype Header file must be included in any program that uses these functions

計算機程式語言 Lecture 國立臺灣大學生物機電系 Character Manipulation Methods Example: If ch is a character variable, consider the following code segment: if(isdigit(ch)) cout << "The character just entered is a digit" << endl; else if(ispunct(ch)) cout << "The character just entered is a punctuation mark" << endl; –If ch contains a digit character, the first cout statement is executed –If ch is a punctuation character, the second statement is executed

計算機程式語言 Lecture 國立臺灣大學生物機電系 Character Manipulation Methods Program 9.14 #include using namespace std; int main() { int i; string str; cout << "Type in any sequence of characters: "; getline(cin,str); // cycle through all elements of the string for (i = 0; i < str.length(); i++) str[i] = toupper(str[i]); cout << "The characters just entered, in uppercase, are: " << str << endl; cin.ignore(); return 0; }

計算機程式語言 Lecture 國立臺灣大學生物機電系 Character I/O Entry of all data from keyboard, whether a string or a number, is done one character at a time –Entry of string Hello consists of pressing keys H, e, l, l, o, and the Enter Key (as in Figure 7.10) All of C++’s higher-level I/O methods and streams are based on lower-level character I/O Table 9.6 lists the basic character I/O methods

計算機程式語言 Lecture 國立臺灣大學生物機電系 Character I/O Figure 9.12 Accepting keyboard entered characters

計算機程式語言 Lecture 國立臺灣大學生物機電系 Character I/O Table 9.6 Basic Character I/O Functions (Require the header file cctype )

計算機程式語言 Lecture 國立臺灣大學生物機電系 Character I/O Table 9.6 Basic Character I/O Functions (Require the header file cctype )

計算機程式語言 Lecture 國立臺灣大學生物機電系 The Phantom Newline Revisited Undesired results can occur when characters are input using the get() character method –Program 9.16 is an example of this problem Two ways to avoid this: –Follow cin.get() input with the call cin.ignore() –Accept the Enter key into a character variable and then don’t use it further Program 9.17 applies the first solution to Program 9.16

計算機程式語言 Lecture 國立臺灣大學生物機電系 The Phantom Newline Revisited Program 9.16 #include using namespace std; int main() { char fkey, skey; cout << "Type in a character: "; cin.get(fkey); cout << "The key just accepted is " << int(fkey) << endl; cout << "Type in another character: "; cin.get(skey); cout << "The key just accepted is " << int(skey) << endl; return 0; }

計算機程式語言 Lecture 國立臺灣大學生物機電系 The Phantom Newline Revisited Program 9.17 #include using namespace std; int main() { char fkey, skey; cout << "Type in a character: "; cin.get(fkey); cout << "The key just accepted is " << int(fkey) << endl; cin.ignore(); cout << "Type in another character: "; cin.get(skey); cout << "The key just accepted is " << int(skey) << endl; cin.ignore(); return 0; }

計算機程式語言 Lecture 國立臺灣大學生物機電系 A Second Look at User-Input Validation Sign of well-constructed, robust program: –Code that validates user input and ensures that program doesn’t produce unintended results caused by unexpected input User-input validation: Basic technique for handling invalid data input and preventing seemingly innocuous code from producing unintended results –Validates entered data during or after data entry and gives the user a way of reentering data if it is invalid

計算機程式語言 Lecture 國立臺灣大學生物機電系 Input Data Validation Validating user input is essential Successful programs anticipate invalid data and prevent it from being accepted and processed A common method for validating numerical input data is accepting all numbers as strings After string is validated it can be converted to the correct type

計算機程式語言 Lecture 國立臺灣大學生物機電系 Input Data Validation Table 9.7 C-String Conversion Functions

計算機程式語言 Lecture 國立臺灣大學生物機電系 Namespaces and Creating a Personal Library C++ provides mechanisms for programmers to build libraries of specialized functions and classes Steps in creating a library: –Optionally encapsulate all of the desired functions and classes into one or more namespaces –Store the complete code in one or more files –namespace syntax: namespace name { functions and/or classes in here } // end of namespace

計算機程式語言 Lecture 國立臺灣大學生物機電系 After a namespace has been created and stored in a file, it can be included within another file –Supply a preprocessor directive informing the compiler where the namespace is to be found –Include a using directive instructing the compiler which particular namespace in the file to use Example: #include using namespace dataChecks; Namespaces and Creating a Personal Library

計算機程式語言 Lecture 國立臺灣大學生物機電系 Namespaces and Creating a Personal Library Program 9.20 #include using namespace dataChecks; int main() { int value; cout << "Enter an integer value: "; value = getanInt(); cout << "The integer entered is: " << value << endl; return 0; }

計算機程式語言 Lecture 國立臺灣大學生物機電系 Common Programming Errors Forgetting to include string header file when using string class object Forgetting that newline character, ‘\n’, is a valid input character Forgetting to convert string class object by using c_str() function when converting string class objects to numerical data types

計算機程式語言 Lecture 國立臺灣大學生物機電系 Summary String literal is any sequence of characters enclosed in quotation marks –Referred to as a string value, a string constant, and, more conventionally, a string String can be can be constructed as an object of the string class string class is common used for constructing strings for input and output purposes Strings can be manipulated by using functions of the class they’re objects of or by using the general purpose string and character functions

計算機程式語言 Lecture 國立臺灣大學生物機電系 Summary cin object tends to be of limited usefulness for string input because it terminates input when a blank is encountered For string class data input, use the getline() function cout object can be used to display string class strings