470 likes | 585 Views
CIS 4930 Application Development Using C++ Dr. Kun Suk Kim CISE Department, University of Florida. Course Introduction. Course Description. This course discusses issues that arise when C++ is used in the design and implementation of software systems.
E N D
CIS 4930Application Development Using C++Dr. Kun Suk KimCISE Department, University of Florida Course Introduction
Course Description • This course discusses issues that arise when C++ is used in the design and implementation of software systems. • The aim is to provide an understanding of how to use the standard library, and to demonstrate general design and programming techniques. • This course (very) briefly and selectively reviews the basic subset of C++.
Course Description • We will cover C++'s facilities (such as templates and operator overloading) for defining families of types and functions. • They demonstrate the basic techniques used to provide containers, such as vectors, and to support generic programming. • During this course we shall use the C++ programming language and standard library.
Topics Include • Templates (function templates and class templates) • Operator overloading feature • Inheritance • Virtual functions • STL fundamental concepts • Containers • Iterators • Generic algorithms • Function objects, etc.
Prerequisites • COP 3530 • Fundamental knowledge of C++
Web Site • http://www.cise.ufl.edu/~mhkim/cis4930sp04/ • Syllabus, text, lectures, assignments, TAs, etc. • My office information
Assignments • Assignment guidelines • Submission procedures
Textbooks • Required Textbook: • The C++ Standard Library: A Tutorial and Reference by Nicolai M. Josuttis, ISBN 0201379260, 1999, 1st ED. • STL and Standard Libraries • Reference Textbook: • Absolute C++ by Walter Savitch, ISBN 0201709279, 2002, Book and CD-ROM edition • Advanced topics in C++
Source Codes • Read instructions to download. • http://www.josuttis.com/libbook/
TAs • TA will answer your questions. • TA will post some announcements on class website related to programming assignments.
Grades • Programming Assignment (40%) • Exam 1 (20%) - February 6, 2004 • Exam 2 (20%) - March 19, 2004 • Final Exam (20%) - April 26, 2004 (26A)
Basic C++ • Variables • Expressions • Assignment statements • Flow of control • Function basics
Flow of Control • Boolean Expressions • Logical AND (&&), Logical OR (||) • Branching Mechanisms • if-else • switch • Nesting if-else • Loops • While, do-while, for • Nesting loops
Precedence of Operators • Scope resolution operator (::) • Dot operator (.), member selection (->), array indexing ([]), function call (()), postfix increment (++), postfix decrement(--) • Prefix increment (++), prefix decrement (--), not (!), unary minus (-), unary plus (+), dereference (*), address of (&), new, delete, delete[], sizeof, type cast (()) • Multiply (*), divide (/), modulo (%) • Addition (+), subtraction (-)
Precedence of Operators • Insertion operator (<<), extraction operator (>>) • <, >, <=, >= • ==, != • && • || • Assignment (=), +=, -=, *=, /=, %= • Conditional operator (? :) • Throw an exception (throw) • Comma operator (,)
Function Basics • Predefined Functions • Return-a-value and void functions • Programmer-defined Functions • Defining, Declaring, Calling • Recursive Functions • Scope Rules • Local variables • Global constants and global variables • Blocks, nested scopes
CIS 4930Application Development Using C++Dr. Kun Suk KimCISE Department, University of Florida Input/Output Using Stream Classes
Objectives • Console I/O • I/O Streams • Tools for Stream I/O • File names as input • Formatting output, flag settings • Stream Hierarchies • Preview of inheritance • Random Access to Files • Ch 13.1-7, 9 (Savitch Ch.12)
Console Input/Output • I/O objects cin, cout, cerr • Defined in the C++ library called<iostream> • Must have these lines (called pre-processor directives) near start of file: • #include <iostream>using namespace std; • Tells C++ to use appropriate library so we canuse the I/O objects cin, cout, cerr
Global Stream Objects • cin • Input stream object connected to keyboard • cout • Output stream object connected to screen • cerr • Standard error channel connected to screen • clog • Standard logging channel connected to screen
Console Output • What can be outputted? • Any data can be outputted to display screen • Variables • Constants • Literals • Expressions (which can include all of above) • cout << number << “ games played.”;2 values are outputted: ‘value’ of variable number, literal string “ games played.” • Cascading: multiple values in one cout
Separating Lines of Output • New lines in output • Recall: ‘\n’ is escape sequence for the char‘newline’ • A second method: object endl • Examples:cout << “Hello World\n”; • Sends string “Hello World” to display, & escapesequence ‘\n’, skipping to next line cout << “Hello World” << endl; • Same result as above
Error Output • Output with cerr • cerr works same as cout • Provides mechanism for distinguishingbetween regular output and error output • Re-direct output streams • Most systems allow cout and cerr to be ‘redirected’ to other devices • e.g.: line printer, output file, error console, etc.
Input Using cin • cin for input, cout for output • Differences: • ‘>>’ (extraction operator) points opposite • Think of it as ‘pointing toward where the data goes’ • Object name ‘cin’ used instead of ‘cout’ • No literals allowed for cin • Must input ‘to a variable’ • cin >> num; • Waits on-screen for keyboard entry • Value entered at keyboard is ‘assigned’ to num
Prompting for Input: cin and cout • Always ‘prompt’ user for inputcout << “Enter number: “;cin >> num; • Note no ‘\n’ in cout. Prompt ‘waits’ on sameline for keyboard input as follows: Enter number: ____ • Underscore above denotes where keyboard entryis made • Every cin should have cout prompt • Maximizes user-friendly input/output
Example #include <cstdlib> #include <iostream> using namespace std; int main(){ double x, y; cout << “Multiplies two floating points" << endl; cout << "first operand: "; if (! (cin >> x)) { // return whether stream run into an error cerr << "error while reading the first value" << endl; return EXIT_FAILURE; } cout << "second operand: ";
Example if (! (cin >> y)) { cerr << "error while reading the second value“ << endl; return EXIT_FAILURE; } cout << x << " times " << y << " equals " << x * y << endl; } Multiplies two floating points first operand: 10 second operand: 10.0 10 times 10 equals 100 Multiplies two floating points first operand: x error while reading the first value
Example • io1 > print (key input) x (key input) error while reading the first value • Content of print file Multiplies two floating points first operand:
Streams and File I/O • Streams • Special objects • Deliver program input and output • File I/O • Uses inheritance • File I/O very useful
Streams • A flow of characters • Input stream • Flow into program • Can come from keyboard • Can come from file • Output stream • Flow out of program • Can go to screen • Can go to file
Streams Usage • Global stream objects • cin, cout, cerr, clog • Can define other streams • To or from files • Used similarly as cin, cout
Streams Usage Like cin, cout • Consider: • Given program defines stream inStreamthat comes from some file:int theNumber;inStream >> theNumber; • Reads value from stream, assigned to theNumber • Program defines stream outStream that goesto some fileoutStream << “theNumber is “ << theNumber; • Writes value to stream, which goes to file
Files • We’ll use text files • Reading from file • When program takes input • Writing to file • When program sends output • Start at beginning of file to end • Other methods available • We’ll discuss this simple text file access here
File Connection • Must first connect file to stream object • For input: • File ifstream object • For output: • File ofstream object • Classes ifstream and ofstream • Defined in library <fstream> • Named in std namespace
File I/O Libraries • To allow both file input and output in yourprogram:#include <fstream>using namespace std; OR#include <fstream>using std::ifstream;using std::ofstream;
Declaring Streams • Stream must be declared like any otherclass variable:ifstream inStream; ofstream outStream; • Must then ‘connect’ to file:inStream.open(“infile.txt”); • Called ‘opening the file’ • Uses member function open • Can specify complete pathname
Streams Usage • Once declared, use normally!int oneNumber, anotherNumber;inStream >> oneNumber >> anotherNumber; • Output stream similar:ofstream outStream;outStream.open(“outfile.txt”);outStream << “oneNumber = “ << oneNumber << “ anotherNumber = “ << anotherNumber; • Sends items to output file
File Names • Programs and files • Files have two names to our programs • External file name • Also called ‘physical file name’ • Like ‘infile.txt’ • Sometimes considered ‘real file name’ • Used only once in program (to open) • Stream name • Also called ‘logical file name’ • Program uses this name for all file activity
Closing Files • Files should be closed • When program completed getting input orsending output • Disconnects stream from file • In action: inStream.close(); outStream.close(); • Note no arguments • Files automatically close when programends
File Flush • Output often ‘buffered’ • Temporarily stored before written to file • Written in ‘groups’ • Occasionally might need to force writing:outStream.flush(); • Member function flush, for all output streams • All buffered output is physically written • Closing file automatically calls flush()
File Example #include <fstream> using std::ifstream; using std::ofstream; using std::endl; int main( ) { ifstream inStream; ofstream outStream; inStream.open("infile.txt"); outStream.open("outfile.txt"); int first, second, third; inStream >> first >> second >> third; outStream << "The sum of the first 3\n“ << "numbers in infile.txt\n" << "is " << (first + second + third) << endl; inStream.close( ); outStream.close( ); return 0; }
File Example • Infile.txt 1 2 3 4 • outfile.txt The sum of the first 3 numbers in infile.txt is 6
Appending to a File • Standard open operation begins withempty file • Even if file exists contents lost • Open for append:ofstream outStream; outStream.open(“important.txt”, ios::app); • If file doesn’t exist creates it • If file exists appends to end • Second argument is class ios defined constant • In <iostream> library, std namespace
Alternative Syntax for File Opens • Can specify filename at declaration • Passed as argument to constructor • ifstream inStream;inStream.open(“infile.txt”); EQUIVALENT TO:ifstream inStream(“infile.txt”);
Checking File Open Success • File opens could fail • If input file doesn’t exist • No write permissions to output file • Unexpected results • Member function fail() • Place call to fail() to check stream operationsuccessinStream.open(“stuff.txt”);if (inStream.fail()){ cout << “File open failed.\n”; exit(1);}
Constants of State of Streams • Type iostate is a member of the class ios_base • Exact type of the constants is an implementation detail • Constants for type iostate • goodbit – Everything is OK; none of the other bit is set • eofbit – End-of-file was encountered • failbit – Error; and I/O operation was not successful • badbit – Fatal error; undefined state
Member Functions Accessing State of Streams • good() - Return true if the stream is OK (goodbit is set) • eof() - Return true if end-of-file was hit (eofbit is set) • fail() - Return true if an error has occurred (failbit or badbit is set) • rdstate() - Return the currently set flags • clear() - Clears all flags • clear(state) - Clears all and sets state flags • setstate(state) - Sets additional state flags