Introduction to Standard C++ Console I/O. C++ Object Oriented Programming Pei-yih Ting NTOU CS

Similar documents
CS2141 Software Development using C/C++ Stream I/O

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Chapter 12 - C++ Stream Input/Output

I/O Streams and Standard I/O Devices (cont d.)

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ Input/Output: Streams

Chapter 3 - Notes Input/Output

Introduction to C++ (Extensions to C)

Fig: iostream class hierarchy

Objects and streams and files CS427: Elements of Software Engineering

Week 3: File I/O and Formatting 3.7 Formatting Output

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

UEE1303(1070) S 12 Object-Oriented Programming in C++

We will exclusively use streams for input and output of data. Intro Programming in C++

Chapter 12. Streams and File I/O

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CS201 Solved MCQs.

File I/O Christian Schumacher, Info1 D-MAVT 2013

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Streams. Rupesh Nasre.

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

CMPS 221 Sample Final

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

CS3157: Advanced Programming. Outline

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

Software Design & Programming I

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

Streams - Object input and output in C++

Sample Code: OUTPUT Daily Highs & Lows

UCA31 - PROGRAMMING IN C++ Unit-1 Principal of OOP Type: 75% Theory & 25 % Numerical Question and Answer

Module C++ I/O System Basics

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Class 14. Input File Streams. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

C++ Programming Lecture 10 File Processing

Setting Justification

Streams in C++ Stream concept. Reference information. Stream type declarations

More File Operations. Lecture 17 COP 3014 Spring april 18, 2018

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

We can even use the operator << to chain the output request as:

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

by Pearson Education, Inc. All Rights Reserved. 2

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

C++ does not, as a part of the language, define how data are sent out and read into the program

Engineering Problem Solving with C++, Etter/Ingber

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Definition Matching (10 Points)

Getting started with C++ (Part 2)

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

C++ Input/Output Chapter 4 Topics

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

10/23/02 21:20:33 IO_Examples

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Introduction to C++ Lecture Set 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1

Writing a Good Program. 7. Stream I/O

CSCI 104 Overview. Mark Redekopp David Kempe

String Variables and Output/Input. Adding Strings and Literals to Your Programming Skills and output/input formatting

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Lecture 4 Tao Wang 1

This watermark does not appear in the registered version - Slide 1

Expressions, Input, Output and Data Type Conversions

Chapter 15 - C++ As A "Better C"

1 Introduction to C++ C++ basics, simple IO, and error handling

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Lab 6. Review of Variables, Formatting & Loops By: Dr. John Abraham, Professor, UTPA

do { statements } while (condition);

COMP322 - Introduction to C++

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Due Date: See Blackboard

Ch 1. Algorithms and Basic C++ Programming

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Unit 1 : Principles of object oriented programming

Course "Data Processing" Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1

Chapter 3. Numeric Types, Expressions, and Output

struct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

IBM. C/C++ Legacy Class Libraries Reference SC

3.1. Chapter 3: The cin Object. Expressions and Interactivity

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Computing and Statistical Data Analysis Lecture 3

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

3.1. Chapter 3: The cin Object in Program 3-1. Displaying a Prompt 8/23/2014. The cin Object

Chapter 3: Expressions and Interactivity

TEST 1 CS 1410 Intro. To Computer Science Name KEY. October 13, 2010 Fall 2010

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

Standard I/O in C and C++

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Object Oriented Programming

Transcription:

Introduction to Standard C++ Console I/O C++ Object Oriented Programming Pei-yih Ting NTOU CS 1

Contents I/O class hierarchy, cin, cout << and >> operators Buffered I/O cin.get() and cin.getline() status of the stream Precise format control: width, precision, fill, grouped formatting flags, manipulators Odds and ends Types of I/O User-defined Types 2

Basic C++ I/O Class Hierarchy C++ performs all I/O through global objects in a class hierarchy ios Defined in <iostream> namespace std { extern istream cin; extern ostream cout; extern ostream cerr; } istream iostream ostream #include <iostream> using namespace std; 3

Insertion operator << The class ostream defines << operator for all the built-in types, ex: Usage: ostream& ostream::operator<<(double x); or ostream& operator<<(ostream& out, double x); double x; cout << 2.54; cout << x; cout << 2.54 << x; Can be extended to handle user-defined types CComplex x; cout << x; sending << message to cout object will be discussed after we introduce operator overloading 4

Extraction operator >> The class istream defines >> operator for all the built-in types, ex: istream& istream::operator>>(double& x); or istream& operator>>(istream& in, double& x); Usage: int x; double y; cin >> x; cin >> y; cin >> x >> y; Can be extended to handle user-defined types CComplex x; cin >> x; will be discussed after we introduce operator overloading 5

Buffered I/O Buffer is implemented by an array of chars, meant to enhance the performance of input/output devices cout buffers the data and does not display immediately int x; cout << "hi" << "\n"; // may not be displayed immediately while (true) x = 10; FILE *fp; cout << "hi" << endl; fflush(fp); A simple trick to force a flush How to flush the buffer if you can t wait until the end of line cout << "hi" << flush << "bye"; cin is buffered until you hit return 6

cin.get() I. istream &istream::get(char &destination); space, tab, newline char cbuf; reference variable cin.get(cbuf); // close to cin >> cbuf; skip white spaces Not skipping white spaces II. istream &istream::get(char *buffer, int length, char delimiter='\n'); read up to length-1 characters or the delimiter character, whichever comes first and store them in the buffer the buffer is automatically terminated with a null char const int kmaxchars = 100; default void main() { delimiter char buffer[kmaxchars]; cin.get(buffer, kmaxchars); } 7

cin.get() This get() does not remove the delimiter character from the stream char buffer1[kmaxchars], buffer2[kmaxchars]; cin.get(buffer1, kmaxchars); // will read string input till \n cin.get(buffer2, kmaxchars); // will read empty string Solution is to the last get() to eat the delimiter cin.get(buffer1, kmaxchars); char dummy; cin.get(dummy); // or cin.ignore(1); cin.get(buffer2, kmaxchars); III. int istream::get(); the purpose of this function is to return EOF, will be useful when the input stream is a file 8

cin.getline() and others istream &istream::getline(char *buffer, int length, char delimiter='\n'); this function is just like the second prototype of get() except that it eats the delimiter istream &istream::ignore(int length=1, int delimiter=eof); skips over length characters or until the delimiter is reached in the istream, whichever comes first the delimiter is also removed from the stream int istream::peek(); Return the next character in the stream without removing it, you can peek for EOF istream &istream::putback(char c); put the char back into the stream 9

Testing the State of the Stream 1. int GetSum() { 2. char baddata; int number, sum; 3. cout << "This program will compute the sum of numbers\ntype zero to quit.\n "; 4. sum = 0; 5. while (true) { 6. cout << "Type a number: "; 7. cin >> number; 8. if (cin.good()) { // input was correct for this type 9. if (number == 0) return sum; 10. sum += number; 11. } 12. else if (cin.fail()) { // error in input type, nothing serious 13. cin.clear(); // reset state bits in the base class 14. cin.get(baddata); // read the bad input as a char 15. cout << baddata << " is not a number."; 16. } 17. else if (cin.bad()) // stream corrupted 18. return sum; 19. } 20. } The base class ios contains a number of state bits which record the correctness of input and the output streams 10

Controlling the Output Format cout.precision() control the number of digits to display for (i=0; i<8; i++) { cout.precision(i); cout << i << ' ' << pi << endl; } cout.width() control the field width width must be set before every output double x=5.6; cout.width(4); cout << x << "first number\n"; cout.width(10); cout << x << "second number\n"; cout.fill() specify the char to be used as spacing cout.fill('.'); cout.width(10); cout << x << "first"; Output: 0 3.14159 1 3 2 3.1 3 3.14 4 3.142 5 3.1416 6 3.14159 7 3.141593 Output: 5.6 first number 5.6 second number Output: 5.6.first 11

Grouped Formatting Flags Certain formatting flags are members of bit groups, ex. Setting scientific or fixed notation double x; x = 6.0225e23; cout.setf(ios::scientific, ios::floatfield); cout << x << '\n'; cout.setf(ios::fixed, ios::floatfield); cout << x << '\n'; Setting justification long x=-2345; cout.width(10); cout.setf(ios::left, ios::adjustfield); cout << x << '\n'; cout.width(10); cout.setf(ios::right, ios::adjustfield); cout << x << '\n'; cout.width(10); cout.setf(ios::internal, ios::adjustfield); cout << x << '\n'; Output: 6.022500e+23 602250000000000000000000.000000 Output: -2345-2345 - 2345 12

Manipulators Special words that perform formatting tasks are called manipulators, ex. cout << pi << endl; cout << "hi" << flush << "bye"; Some I/O member functions have manipulator equivalents cout << setw(4) << x << setw(10) << y; setw() is the parameterized manipulator equivalent of cout.width() manipulator can be embedded within I/O statements #include <iomanip> Other examples: setprecision(4) cout.precision(4) setfill('x') cout.fill('x') 13

Odds and Ends White spaces are skipped during stream extraction You can turn this feature on or off char x; cin.unsetf(ios::skipws); cin >> x; cout << x; cin.setf(ios::skipws); // turn off skipping white space // turn on skipping white space User-defined stream manipulators define tab manipulator ostream &tab(ostream &currentstream) { return currentstream << '\t'; } Usage: cout << tab << 'Z'; 14

Odds and Ends Change the display to another base cout.setf(ios::hex, ios::basefield); // ios::dec, ios::oct or using manipulators cout << setbase(16) << x; // 8, 10 or 16 Current format settings cout << cout.precision() << '\n'; cout << cout.width() << '\n'; cout << cout.fill() << '\n'; Forcing floating-point displays double x=7; cout << x << '\n'; cout.setf(ios::showpoint); // no group cout << x << '\n'; or using manipulators cout << showpoint << x << '\n'; Output: 6 0 <space> Output: 7 7.00000 15

Types of I/O Plain vanilla applications Input: user types in commands / Output: text written to a console window Dialog window approach (MFC) CMyInputDialog dlg; dlg.data = "initial data"; // output dlg.domodal(); strcpy(targetstr, dlg.data); // input Explicit CFile class approach (MFC) CFile infile; CFileException e; if (!infile.open("test.dat", CFile::modeCreate CFile::modeWrite, &e ) ) Archive serialization approach (MFC) void CAge::Serialize( CArchive& ar ) { CObject::Serialize( ar ); if ( ar.isstoring()) ar << m_years; else ar >> m_years; } 16

User-defined Types Old way, not suitably encapsulated: CComplex number1(4, 2), number2(3, 1); CComplex sum; Sum = number1 + number2; cout << sum.getreal() << " + " << sum.getimaginary() << 'i'; Encapsulated: cout << sum << endl; ostream &operator<<(ostream &os, CComplex number) { os << number.m_real << " + " << number.m_imaginary << 'i'; return os; } 17