multiple inheritance aside how to safely read data
play

Multiple inheritance Aside: how to safely read data Execute - PDF document

Multiple inheritance Aside: how to safely read data Execute /hw4/array enter junk (after 1 st iteration) Can derive a class from more than one base class Use ctrl-C to stop the infinite loop, because that e.g., class


  1. Multiple inheritance Aside: how to safely read data � Execute …/hw4/array – enter “junk” (after 1 st iteration) � Can derive a class from more than one base class – Use ctrl-C to stop the infinite loop, because that � e.g., class Appliance; program is not “crash-proofed” at all class Radio : virtual public Appliance; � See a better way in …/demo10/goodflush/ class AlarmClock : virtual public Appliance; class ClockRadio : public Radio, public AlarmClock; – If bad data, clear error bits in cin – cin.clear() – A ClockRadio is both a Radio and an AlarmClock – – Then must remove the bad data from the input stream so it is also an Appliance � e.g., read it into a C string like the example programs – Note virtual – just 1 Appliance subobject, not 2 � Note: Nagler technique (p. 443-4) doesn’t work – See ClockRadio example: …/demo08/multi-inherit – Becoming a theme? Try it in …/demo10/badflush � But note: hierarchy is messed up – best to avoid Other C++ input/output notes More C++ I/O notes � Manipulators – functions with special signatures � std::ios_base – atop the iostream hierarchy that are invoked by << and >> – Many public constants and functions – Lots of built-in manipulators – e.g., cout.width(5); cout.setf(ios_base::right); … cout << right << setw(5) << ‘a’ << endl; � #include <sstream> – for string streams – Easy to write your own too – chapter 16 shows how – ostringstream oss; // now use oss just like cout � File I/O – use ifstream and ofstream objects � Get the string when done – e.g., cout << oss.str(); � Can do character I/O just as easily as in C – Once opened, treat like cin and cout , respectively – Use cin.get() and cout.put(char) – Simplest way is to open on construction � Line input is easy too – good for crash-proofing � ofstream out(“myfile”); out << “my data\n”; – Use cin.getline( C-string, size [, delim_char] ) – Easy to learn other file techniques from chapter 17 std::string Standard template library (STL) � Object-oriented way to deal with character strings � A framework of generic containers and algorithms � Actually defined type for basic_string<char> – STL containers are class templates – for storing and accessing parameterized data types – Other: typedef basic_string<wchar_t> wstring; – STL algorithms are function templates – mostly � Must #include <string> to use these types involving contents of STL containers � Most of the features of Nagler’s class String � Iterators are the framework’s linchpins – And more: overloaded ops = , + , += , [] , all relational – Essentially pointers to container elements ops, plus insert() , substr() , getline() , … � In fact, pointers into arrays can usually qualify – No conversion op – use c_str() function to get char* – Each container type has a set of possible iterators � See stringDemo() function in – The algorithms access container elements using these ~cs60/demo10/librarytools.cpp iterators – so their use is standardized across containers 1

  2. STL sequence containers Adaptive sequence containers � vector<typename> – basically a smart array � Underlying data structure is other sequence – Can even access random elements with [] – But access is restricted in some defined way – Unlike arrays, vector s grow dynamically as required, and have � stack<typename> – LIFO access methods like size() , empty() , clear() , insert() , … – Basic operations are push() , pop() , and top() – See vectorDemo function in librarytools.cpp � list<typename> – a double-linked list � queue<typename> – FIFO access – Quick insertion and removal of elements – Operations are push() , pop() , and front() – No random access – but has bi-directional iterators providing � priority_queue<typename> access relative to existing elements – push() , pop() , and top() (like stack, not queue) � deque<typename> – a vector/list combination � But pop() and top() access highest priority element Associative containers STL algorithms � Designed for accessing data by search keys � Function templates – mostly work with iterators – Main feature – quick insert() and find() operations – Idea – alternative to algorithms built into containers – Also feature a natural ordering of the data elements � Facilitates consistent handling of the various containers � Sets – the data are the keys � Usual: alg(iterBegin, iterEnd, other args ) – set<typename, functor> – no duplicates – e.g., fill(vector.begin(), vector.end(), 0); � The functor is used to order the elements – e.g., random_shuffle(v.begin(), v.end()); – For duplicates: multiset<typename, functor> – More examples in …/demo10/librarytools.cpp � Maps – elements are key/data pairs � One last thing – complete STL documentation is – map<keyT, dataT, functor> , or allow duplicates available online at http://www.sgi.com/tech/stl/ with multimap< keyT, dataT, functor> Unix shells Bourne shell programs � Are text files with sh commands – e.g., myScript � Unix systems come with a variety of shells – Most common: Bourne ( sh ), C ( csh ) and Korn ( ksh ) – To execute, can do sh myScript – Newer: Bash ( bash ) and TC ( tcsh ) � The program runs in a new shell – called a child shell – Or chmod u+x myScript – then just myScript � Primary purpose – interpret user commands � But might not work if sh is not default shell – So a.k.a. command interpreters � # – usually identifies a comment – Essentially interfaces to Unix kernel – Special case if line 1 – #!/bin/sh – identifies shell � The kernel is the actual operating system program � Means use sh as child shell for this script – works in all shells � Also programming languages in their own rights � Can access command line arguments: $1 to $# – Shell programs – series of shell commands, but also – e.g., cp $1 $2 # copies first to second (if files) variables, conditional branching, loops, functions, … – e.g., echo $# # prints number of arguments – A.k.a. scripts – are interpreted languages 2

  3. sh variables and assignment sh control structures � name=“Jack Sprat” # note no spaces � An if-then-elif-else-fi statement � echo “The name is $name” # need ‘ $ ’ – Expression is a test: test $# -gt 0 � workdir=`pwd` # use `…` to assign result of … – Or simpler: [ $# -gt 0 ] # spaces mandatory – Can test files too: -d , -f , -e , -r , -w , -x , … – Similarly, echo “date and time is `date`” � A while statement – same expressions � Can read from standard input and calculate too – echo “enter value” � A for statement – for variable in list – read val – List is command line arguments if not specified – doubleval=`expr $val + $val` � See ~cs60/demo10 for examples ( sh examples have “demo” in filenames) � Or just: echo “doubled: `expr $val + $val`” C shell programs Perl – a command language � csh – can look a bit more like C programs � Not a shell – but interprets and compiles scripts – e.g., use $argv[1] instead of $1 – Compiles at start of execution – to run loops much faster – if-then-else-endif – i.e., no fi or elif � Written by a linguist, not a CS person – Larry Wall � Expressions more natural too: () , == , > , || , && , … – Practical Extraction Report Language – more versatile than shell – while and switch structures also more like C scripts, but less complicated than C programs � print “hello world.\n”; # note C-like syntax � Some things weirder than Bourne shell though � $name = “John Smith”; # need ‘$’ even for first use – Need set for assignment, or @ if numeric � Has arrays, and associative arrays (lookup tables) – Reading input is awkward: set x = `head –1` � Also string operators; C-like if , while , for ; file I/O; � But can use arrays, and system calls easier functions; and access to library functions – See *.csh examples in …/demo10 � See …/demo10/loan.pl (many more at www.perl.com ) � Learn about shell syntax with man – csh, sh, … 3

Recommend


More recommend