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

Slides:



Advertisements
Similar presentations
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
Advertisements

 2006 Pearson Education, Inc. All rights reserved Stream Input/Output.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 11 Chapter 21 - C++ Stream Input/Output Outline 21.1Introduction.
Chapter 3: Input/Output
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 27P. 1Winter Quarter I/O Manipulation Lecture.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
CSCE 121: Introduction to Program Design and Concepts J. Michael Moore Fall 2014 Set 11: More Input and Output 1 Based on slides created by Bjarne.
1 Advanced Input and Output COSC1567 C++ Programming Lecture 9.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 11 Customizing I/O Bjarne Stroustrup
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
C++ Streams Lecture-2.
1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output.
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.
C++ Streams Lecture-2. C++ Streams Stream  A transfer of information in the form of a sequence of bytes I/O Operations:  Input stream: A stream that.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 31 Thanks for Lecture Slides: C How to Program by Paul Deital &
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1436 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah Alakeel.
1 Today’s Objectives  Announcements Turn in Homework 4 Quiz 4 will be on Wednesday, July 19 – It will have questions about inheritance, polymorphism,
Streams, and File I/O Review. STREAMS Review STREAMS Streams are sequences of bytes. C++ I/0 occurs in streams Input – bytes flow from device to memory.
Chapter -7 Basic function of Input/output system basics and file processing Stream classes : I/O Streams. A stream is a source or destination for collection.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 4 Working with Data Files.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
CSE 332: C++ data types, input, and output Built-In (a.k.a. Native) Types in C++ int, long, short, char (signed, integer division) –unsigned versions too.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
C++ How to Program, 8/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Chapter 13 Stream Input/Output C++ How to Program, 9/e © Copyright 2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
What is wrong in the following function definition
Introduction to C++ (Extensions to C)
C++ Basic Input and Output (I/O)
CPS120: Introduction to Computer Science
TMF1414 Introduction to Programming
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
Chapter 21 - C++ Stream Input/Output Stream Manipulators
Output Stream Formatting
Basic Input and Output Operations
Chapter 21 - C++ Stream Input/Output
Chapter 2 part #3 C++ Input / Output
06 – Software Design P.9 Input / Output Using Streams
10 – Iterators C++ Templates 4.6 The Iterator pgs
Standard Input/Output Streams
Standard Input/Output Streams
Lecture 5A File processing Richard Gesick.
Advanced Input and Output
More About Data Types & Functions
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Chapter 13: Advanced File and I/O Operations
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Chapter 3: Input/Output
Why Use Namespaces? Classes encapsulate behavior (methods) and state (member data) behind an interface Structs are similar, but with state accessible Classes.
Topics Input and Output Streams More Detailed Error Testing
Chapter 3 Input output.
Chapter 4 INPUT AND OUTPUT OBJECTS
Programming with ANSI C ++
Chapter 2 part #3 C++ Input / Output
C++ Programming Lecture 8 File Processing
ENERGY 211 / CME 211 Lecture 9 October 10, 2008.
Input/Output Streams, Part 2
Presentation transcript:

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. 33-58 For Next Time… Software Design, 1.1-3, pgs. 63-98

Attendance Quiz #4 C++ Primer

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; }; http://syque.com/cstyle/contents.htm

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. 33-37

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

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(3.1415926); new std::string(line, 5, 10); int** a = new int*[rowCount]; for(int i = 0; i < rowCount; ++i) a[i] = new int[colCount];

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

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;

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…

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. 38-43

Stream Class Hierarchy C++ Primer Input Output

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.

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.

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');

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.)

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

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

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)

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;

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; }

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;