Input/Output. Stream I/O. Stream Sequence of bytes that may be input to, or output from, a program. Three standard streams in C++

Similar documents
C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

C++ Input/Output: Streams

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Basics of I/O Streams and File I/O

Formatting Numbers with C++ Output Streams

Member Functions of the istream Class

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

C++ Language Tutorial

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Sequential Program Execution

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

The Payroll Program. Payroll

Number Representation

Using C++ File Streams

The C Programming Language course syllabus associate level

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Chapter One Introduction to Programming

7.7 Case Study: Calculating Depreciation

Passing 1D arrays to functions.

Subject Name: Object Oriented Programming in C++ Subject Code:

El Dorado Union High School District Educational Services

Answers to Review Questions Chapter 7

The little endl that couldn t

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

An Incomplete C++ Primer. University of Wyoming MA 5310

Oct: 50 8 = 6 (r = 2) 6 8 = 0 (r = 6) Writing the remainders in reverse order we get: (50) 10 = (62) 8

Numbering Systems. InThisAppendix...

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

C++ INTERVIEW QUESTIONS

Base Conversion written by Cathy Saxton

Ubuntu. Ubuntu. C++ Overview. Ubuntu. History of C++ Major Features of C++

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

So far we have considered only numeric processing, i.e. processing of numeric data represented

Pemrograman Dasar. Basic Elements Of Java

Binary storage of graphs and related data

CSI 333 Lecture 1 Number Systems

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Chapter 4: Computer Codes

Storing Measurement Data

C++ Essentials. Sharam Hekmat PragSoft Corporation

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Sources: On the Web: Slides will be available on:

Compiler Construction

Chapter 2: Elements of Java

Java Interview Questions and Answers

5 Arrays and Pointers

Binary Number System. 16. Binary Numbers. Base 10 digits: Base 2 digits: 0 1

The string of digits in the binary number system represents the quantity

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Informatica e Sistemi in Tempo Reale

UEE1302 (1102) F10 Introduction to Computers and Programming

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)

How To Write Portable Programs In C

Machine Architecture and Number Systems. Major Computer Components. Schematic Diagram of a Computer. The CPU. The Bus. Main Memory.

Decimal to Binary Conversion

JAVA - FILES AND I/O

Stacks. Linear data structures

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine

Section 1.4 Place Value Systems of Numeration in Other Bases

HOMEWORK # 2 SOLUTIO

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Objective-C Tutorial

Answers to Selected Exercises

The programming language C. sws1 1

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

File Handling. What is a file?

Operating Systems. Privileged Instructions

Data Storage: Each time you create a variable in memory, a certain amount of memory is allocated for that variable based on its data type (or class).

Systems I: Computer Organization and Architecture

This 3-digit ASCII string could also be calculated as n = (Data[2]-0x30) +10*((Data[1]-0x30)+10*(Data[0]-0x30));

Useful Number Systems

sqlite driver manual

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Appendix K Introduction to Microsoft Visual C++ 6.0

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

Lecture 11: Number Systems

Programming languages C

plc numbers Encoded values; BCD and ASCII Error detection; parity, gray code and checksums

IBM Emulation Mode Printer Commands

Lab 4: Socket Programming: netcat part

Computers. Hardware. The Central Processing Unit (CPU) CMPT 125: Lecture 1: Understanding the Computer

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Fondamenti di C++ - Cay Horstmann 1

While Loop. 6. Iteration

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

public static void main(string[] args) { System.out.println("hello, world"); } }

Module 816. File Management in C. M. Campbell 1993 Deakin University

C++ Programming Language

2 ASCII TABLE (DOS) 3 ASCII TABLE (Window)

DNA Data and Program Representation. Alexandre David

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Transcription:

Input/Output Stream I/O Stream Sequence of bytes that may be input to, or output from, a program Three standard streams in C++ 1. cin Standard input stream (stdin) 2. cout Standard output stream (stdout) 3. cerr Standard error stream (stderr) cin and cout are buffered streams while cerr is unbuffered The << and >> operators The cin >> and cout << operators are overloaded >> and << operators, applied to members cin and cout of the classes istream and ostream, defined in iostream.h Why can the operators be chained together (like cout << x << y;)? The operator << binds left to right The above expression can be fully parenthesized as ( cout << x ) << y; Furthermore, each << operation returns a value that is identical to its first argument Since ostreams are fairly sizable objects, the operator<< functions take an ostream& and return it The definition of the operator inside the class is ostream& operator<< ( ostream&, char* ); ostream& operator<< ( ostream&, int ); Defining << for user-defined classes (example complex) class complex double re, im; public: complex ( double, double ); friend ostream& operator<< ( ostream&, const complex& ); friend istream& operator>> ( istream&, complex& ); ; complex::complex ( double r = 0.0, double i = 0.0 ) re = r; im = i; ostream& operator<< ( ostream& s, const complex& c ) return ( s << c.re << " + i" << c.im );

Input/Output 2 istream& operator>> ( istream& s, complex& c ) s >> c.re; char ch; s >> ch; if ( ch!= + ) cout << "+ expected" << endl; s >> ch; if ( ch!= i ) cout << "i expected" << endl; s >> c.im; return s; complex c ( 5.0, 3.0 ); cout << "The complex number is: " << c << endl; I/O of characters and strings We can put a single character on the output stream by using the function The function is called as A character is input by ostream::put ( char ) cout.put ( ch ) cin.get ( ch ) get reads a whitespace character rather than skipping over it You can put the character back on the input stream by cin.putback ( ch ) You can examine a character without removing it from input stream by Two functions for line-based input cin.peek ( ch ) istream& istream::getline ( char * buffer, int bufsize, char terminator = \n ); istream& istream::get ( char * buffer, int bufsize, char terminator = \n ); cin.getline ( line, 80 ); reads a line cin.get ( word, 20, ); reads in a word because the termination character is changed to a space The termination character is left as the next character on the input stream when calling get, whereas getline extracts the termination character and throws it away

Input/Output 3 Both functions automatically place a null string terminator in the buffer, and stop reading when the buffer is full You can call istream::gcount() immediately after any of these two functions to get the number of characters transferred into the buffer Formatted I/O Formatting (binary to ASCII and the other way round) is automatically performed by the class ios, the base class for both istream and ostream Formatting is governed by a format state in the ios class The format state contains Field width Fill character Field alignment Integer base (decimal, hex, octal) Floating point format (fixed, scientific, general) Whether to show a + sign, trailing decimal point and zeroes, or the integer base Uppercase or lowercase letter usage for E, 0X, hex digits To manipulate these states, you need to #include <iomanip.h> in your function Each of the states can be changed in two ways 1. With an ios function manipulator The ios function manipulators return the old values of the manipulated parameter, making it convenient to restore the old values if needed 2. With a manipulator To set the fill character to 0 and the width to 10, you can use cout.fill ( 0 ); cout.width ( 10 ); or cout << setfill ( 0 ) << setw ( 10 ); Setting field width For output, field width denotes the minimum number of characters printed for a field For input, width is meaningful only if reading a string Except for field width, the members of format state are implemented with bits or groups of bits Bits can be turned on with the member function ios::setf or a manipulator setiosflags Bits can be turned off with the member function ios::unsetf or a manipulator resetiosflags To show a leading + sign for positive numbers, you can use either of the following: cout.setf ( ios::showpos ); cout << setiosflags ( ios::showpos );

Input/Output 4 The flag can be turned off by cout.unsetf ( ios::showpos ); cout << resetiosflags ( ios::showpos ); For more than two choices (such as decimal, hex, or octal base), you need to make two selections The available flags are: Illustrating different features #include <iostream.h> #include <iomanip.h> cout.setf ( ios::hex, ios::basefield ); ios flag Field group Meaning left adjustfield Left alignment right adjustfield Right alignment internal adjustfield Sign left, remainder dec basefield Decimal base hex basefield Hex base oct basefield Octal base showbase Show integer base showpos Show + sign uppercase Uppercase E, X, and A...F fixed floatfield Fixed floating-point scientific floatfield Scientific floating-point showpoint Show trailing decimal point cout << setfill( 0 ) << setw ( 10 ); cout << 42.84 << endl; cout.setf ( ios::left, ios::adjustfield ); cout << setfill( * ) << setw ( 20 ) << "Hello World!" << endl; cout.setf ( ios::right, ios::adjustfield ); cout << setw ( 20 ) << "Hello World!" << endl; cout.setf ( ios::scientific, ios::floatfield); cout.setf ( ios::showpoint ios::showpos ); cout << setprecision ( 10 ) << 123.45678 << endl; cout.unsetf ( ios::floatfield); cout << setprecision ( 10 ) << 123.45678 << endl; int n = 12; cout.unsetf ( ios::showpos ); cout << hex << n << << oct << n << << dec << n << endl; Available manipulators

Input/Output 5 Manipulator setfill setw setprecision setiosflags resetiosflags hex oct dec ios member function fill width precision setf unsetf The only saving grace compared to C I/O handling is that C++ completely avoids the mismatch between the format string and the data type Using files for I/O You must include the header file fstream.h To open a stream attached to a file ifstream is ( "input.txt", ios::in ); ofstream os ( "output.txt", ios::out ); The classes ifstream and ofstream are derived from istream and ostream An [io]fstream object is an [io]stream object with added capabilities You can use all the [io]stream functions (<<, get, putback) with [io]fstream objects Example to read something from terminal and put it to a file #include <iostream.h> #include <fstream.h> char ch, line[80]; // Open output stream for file outfile ofstream os ( "outfile", ios::out ); while (!( ch = cin.eof() ) ) cin.getline ( line, sizeof(line) ); os << line << endl; // Close the output stream os.close(); If a file cannot be opened, the [io]fstream variable gets 0 and can be checked if (! os ) cerr << "Error opening file" << endl;

Input/Output 6 Error states All I/O streams have a state associated with them from the set good, end-of-file, fail, bad Fail state Occurs because of a logical error, such as trying to read an integer when the next character is a letter Bad state Occurs because of a physical error, such as a hardware failure or memory exhaustion The stream state is reported by four access functions 1. good() 2. eof() 3. bad() 4. fail() fail() is true if the stream is in fail or bad state eof() is true if the end of file is reached and the stream is not in a failed state The states can be tested with the rdstate member function if ( s.rdstate() & ios::failbit ) The stream can be reset to good state with s.clear(); or to fail with s.clear ( ios::failbit s.rdstate() ); You may need to clear the state if you want to continue reading after the state has been set to bad or fail You may need to set the state to bad to report problems in the user-defined operator>> Attaching streams to strings Equivalent to sscanf Achieved by the string stream package #include <iostream.h> #include <strstream.h> char line[80]; int i; double d; istrstream si ( line, sizeof ( line ) );

Input/Output 7 while ( cin.getline ( line, sizeof ( line ) ) ) si >> i >> d; si.seekg ( ios::beg ); //reset to start cout << i << << d << endl; The output stream is declared with ostrstream so ( line, sizeof ( line), ios::out ); and is reset with so.seekp ( ios::beg );