Presentation is loading. Please wait.

Presentation is loading. Please wait.

Friday, January 19, 2018 Announcements… For Today… For Next Time…

Similar presentations


Presentation on theme: "Friday, January 19, 2018 Announcements… For Today… For Next Time…"— Presentation transcript:

1 Friday, January 19, 2018 Announcements… For Today… For Next Time…
C++ Primer Announcements… Lab 1: Grades due Friday 01/26 Pre-exam results 364/400 For Today… C++ Primer, P.7-9, pgs For Next Time… Software Design, 1.1-3, pgs

2 Attendance Quiz #4 C++ Primer

3 Tip #5: Toothbrushes vs. Combs
C++ Primer When an item is followed by a related group of items, there are two layout possibilities. The 'toothbrush' layout has a handle which sticks out a long way, with the bristles at the end. This makes the handle very visible and easy to find and read: struct CHAR_TYPE { unsigned int FontName; unsigned int Point; }; However, this causes tramping across the page towards the right margin. A list of such items may also result in uneven, less readable, indentation. A more common approach is to use the 'comb' layout, which has only a small handle, with the bristles in a standard position below it: struct CHAR_TYPE { unsigned int FontName; unsigned int Point; };

4 P.7 Arrays and C Strings P.7, pgs. 33-37 Array-Pointer Equivalence
Array Arguments String Literals and C Strings Multidimensional Arrays P.7, pgs

5 Arrays and Pointers An array is a sequence (in memory) of like items.
C++ Primer An array is a sequence (in memory) of like items. In C and C++, arrays are NOT data types. The array size must be explicit at compile time. Zero based subscripts. No compile-time or run-time limit checking. Array names are NOT pointer variables. char a[6]; Requests memory for 6 characters, to be known by the name “a”. “a” is known only at compile time (ie. compiler symbol table). char *p; “p” is a pointer variable and can point to any char (or array of chars). Example: \0 o l e h a: char a[] = "hello"; char *p = "world"; p: \0 d l r o w

6 Dynamic Objects C++ Primer In C++ programs, we generally do not initialize points using the address-of operator. Instead, pointer are used to refer to dynamically created objects using the new operator and destroyed using the delete operator. new type-name new type-name(initial-value) new class-name(parameters) new double; new double( ); new std::string(line, 5, 10); int** a = new int*[rowCount]; for(int i = 0; i < rowCount; ++i) a[i] = new int[colCount];

7 Strings Are Really Templates
P.8 The string Class Strings Are Really Templates P.8, pgs 38-43

8 Template Classes C++ Primer "Instantiation-style polymorphism" means that the template MyClass<T> isn't really a generic class that can be compiled to code that can work for any value of T. Add overhead such as boxing (convert value types to objects), needing to pass function pointers to allocators and constructors, etc. C++ templates avoid having to write nearly identical classes (int, float, etc.), but to still be able to end up with compiled code that is mostly as if we had written each version separately. A template is literally a template; a class template is not a class, it's a recipe for creating a new class for each type T. A template cannot be compiled into code, only the result of instantiating the template can be compiled. typedef basic_string<char> string;

9 Strings vs Character Arrays
C++ Primer Character arrays Size allocated statically. More memory cannot be allocated at run time. Unused allocated memory is wasted. Strings Size allocated dynamically. Memory allocated at run time on demand. Memory is pre-allocated, no memory is wasted. Threat of array decay (loss of type and dimensions when passing an array into function by value or pointer). As strings are represented as objects, no array decay occurs. std:: string slower with object construction. Implementations are fast. No inbuilt functions to manipulate strings. (string.h library w/strcpy, strcat, strlen, strcmp, …) String class functions: Input functions (3), Capacity functions (3), Iterator functions (4), Manipulating functions (2), and more…

10 P.9 Input / Output Using Streams
Console Input / Output Input Streams Output Streams Formatting Output Using I/O Manipulators File Streams openmode String Streams P.8, pgs

11 Stream Class Hierarchy
C++ Primer Input Output

12 C++ Streams C++ Primer A stream is an entity where a program can either insert or extract characters. Abstracts character I/O operations on sequential media such as the screen, the keyboard, or a file. The standard input stream by default is the keyboard and the istream object defined to access it is cin. The standard output stream by default is the screen and the ostream object defined to access it is cout. File I/O classes are derived directly or indirectly from the classes istream and ostream: ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files. File streams associate streams with physical files.

13 State of Streams C++ Primer The steam superclass ios_base maintains a data member to describe the states of the stream, which is a bitmask of the type iostate. The flags are: eofbit: set when an input operation reaches end-of-file. failbit: The last input operation failed to read the expected characters or output operation failed to write the expected characters, e.g., getline() reads n characters without reaching delimiter character. badbit: serious error due to failure of an IO operation (e.g. file read/write error) or stream buffer. goodbit: Absence of above error with value of 0. These flags are defined as public static members in ios_base. They can be accessed member functions of ios class: good(): returns true if goodbit is set (i.e., no error). eof(): returns true if eofbit is set. fail(): returns true if failbit or badbit is set. bad(): returns true if badbit is set. clear(): clear eofbit, failbit and badbit.

14 Input Streams An input stream is a sequence of characters.
C++ Primer An input stream is a sequence of characters. The class istream defines the extraction operator (>>) for primitive data types. Input comes from input console, input file, or network socket. Breaks input into groups of characters separated by spaces. Upon error, error flag is set and the stream freezes. Function getline (from header <string>) reads whole line. istream& getline(istream&, string&, char delim = '\n'); Flush input line after insertion error: cin >> var; if (bad()) cin.ignore(numeric_limits<int>::max() '\n'); getline(cin, name, '\n');

15 Output Streams C++ Primer An output stream is a sequence of characters that can be displayed on the console, written to an output file, or written to a network socket. The class ostream defines the insertion operator (<<) for primitive types. Type Processing char Character is output. string The sequence of characters in the string is output. int, short, long The integral value is converted to decimal and characters are output. (Leading zeros are suppressed, preceded by "-" if negative.) float, double, long double The floating-point value is converted to a decimal representation and output. (Default is 6 digits, numbers between 10-4 and 106 are output in fixed format, otherwise scientific format.)

16 I/O Manipulators C++ Primer C++ provides various stream manipulators that perform formatting tasks. Stream manipulators are defined in <iomanip>. Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects. These manipulators provide capabilities for setting field widths (setw), setting precision (setprecision), setting and unsetting format flags, flushing streams, inserting a "newline" and flushing output stream, skipping whitespace in input stream

17 Basic Format Flags Independent flags (switch on/off) Parameterized
C++ Primer Independent flags (switch on/off) (no)boolalpha Alphanumerical bool values (function) (no)showbase Show numerical base prefixes (function) (no)showpoint Show decimal point (function) (no)showpos Show positive signs (function) (no)skipws Skip whitespaces (function ) (no)unitbuf Flush buffer after insertions (function) (no)uppercase Generate upper-case letters (function) Parameterized Manipulators setiosflags Set format flags (function) resetiosflags Reset format flags (function) setbase Set basefield flag (function) setfill Set fill character (function) setprecision Set decimal precision (function) setw Set field width (function), not sticky

18 Numerical, Floating Point
Basic Format Flags C++ Primer Numerical, Floating Point and Format Flags dec Use decimal base (function) hex Use hexadecimal base (function) oct Use octal base (function) fixed Use fixed floating-point notation (function) scientific Use scientific floating-point notation (function) internal Insert characters at an internal position (function) left Adjust output to the left (function ) right Adjust output to the right (function ) Output endl Insert newline and flush (function ) ends Insert null character (function) flush Flush stream buffer (function)

19 File Streams // reading a text file #include <iostream>
C++ Primer // reading a text file #include <iostream> #include <fstream> #include <string> using namespace std; int main () { string line; ifstream myfile("example.txt"); if (myfile.is_open()) while (getline(myfile, line)) cout << line << '\n'; } myfile.close(); else cout << "Unable to open file"; return 0; // writing on a text file #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile("example.txt"); if (myfile.is_open()) myfile << "This is a line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0;

20 String Streams #include <string> #include <cstring>
C++ Primer #include <string> #include <cstring> #include <sstring> using namespace std; int main(int argc, char* argv[]) { if (argc < 3) return 1; ostringstream argsOut; argsOut << argv[1] << " " << argv[2]; istringstream argsIn; double f, g; argsIn >> f; argsIn >> g; cout << f << "/" << g << "=" << f/g << endl; return 0; }

21 File or Console #include <iostream> #include <fstream>
C++ Primer #include <iostream> #include <fstream> #include <string> using namespace std; int main(int argc, char* argv[]) { ifstream in(argv[1]); if (in) ostream& out = (argc > 2) ? *(new ofstream(argv[2])) : cout; while (!in.eof()) string line; getline(in, line); out << line << endl; } if (&out != &cout) delete(&out); in.close(); else cout << "Unable to open file"; return 0;

22


Download ppt "Friday, January 19, 2018 Announcements… For Today… For Next Time…"

Similar presentations


Ads by Google