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

Similar documents
Chapter 3: Input/Output

Chapter 3 - Notes Input/Output

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

C++ Programming: From Problem Analysis to Program. Design, Fifth Edition. Chapter 1: An Overview of Computers and Programming Languages

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

C++ Input/Output: Streams

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

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

Software Design & Programming I

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

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

Engineering Problem Solving with C++, Etter/Ingber

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

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

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

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

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.

C++ Input/Output Chapter 4 Topics

Definition Matching (10 Points)

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

C++ Programming Lecture 10 File Processing

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

Chapter 3. Numeric Types, Expressions, and Output

Introduction to C++ (Extensions to C)

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

Objectives. In this chapter, you will:

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

Lecture 3 The character, string data Types Files

Module C++ I/O System Basics

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

What we will learn about this week:

Expressions, Input, Output and Data Type Conversions

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

Setting Justification

Chapter 2. Outline. Simple C++ Programs

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

Streams - Object input and output in C++

by Pearson Education, Inc. All Rights Reserved. 2

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

CPE Summer 2015 Exam I (150 pts) June 18, 2015

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

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

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

COMP322 - Introduction to C++

Getting started with C++ (Part 2)

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

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.

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14

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

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

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

Chapter 12. Streams and File I/O

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

Chapter 12 - C++ Stream Input/Output

Chapter 2 Basic Elements of C++

BITG 1233: Introduction to C++

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

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

Chapter 21 - C++ Stream Input/Output

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

Understanding main() function Input/Output Streams

Lab # 02. Basic Elements of C++ _ Part1

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York

CS201 Solved MCQs.

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

Input/Output Streams: Customizing

Window s Visual Studio Output

Chapter 21 - C++ Stream Input/Output

PROGRAMMING EXAMPLE: Checking Account Balance

CHAPTER 3 Expressions, Functions, Output

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

Chapter 14 Sequential Access Files

Object Oriented Programming Using C++ UNIT-3 I/O Streams

READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties. Do not start the test until instructed to do so!

Lecture 4 Tao Wang 1

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.

CS3157: Advanced Programming. Outline

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

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

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

Objects and streams and files CS427: Elements of Software Engineering

A SHORT COURSE ON C++

Introduction to Programming EC-105. Lecture 2

Object Oriented Programming In C++

WARM UP LESSONS BARE BASICS

Chapter 11 Customizing I/O

Name Section: M/W T/TH Number Definition Matching (8 Points)

Chapter 2: Introduction to C++

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

The C++ Language. Arizona State University 1

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

COMP322 - Introduction to C++

Transcription:

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 from the standard input device Learn how to use predefined functions in a program Explore how to use the input stream functions get, ignore, putback, and peek Objectives Become familiar with input failure Learn how to write data to the standard output device Discover how to use manipulators in a program to format output Learn how to perform input and output operations with the string data type Learn how to debug logic errors Become familiar with file input and output 3 4 I/O Streams and Standard I/O Devices I/O: sequence of bytes (stream of bytes) from source to destination Bytes are usually characters, unless program requires other types of information Stream: sequence of characters from source to destination Input stream: sequence of characters from an input device to the computer Output stream: sequence of characters from the computer to an output device I/O Streams and Standard I/O Devices Use iostream header file to receive data from keyboard and send output to the screen Contains definitions of two data types: istream: input stream ostream: output stream Has two variables: cin: stands for common input cout: stands for common output 5 6 1

I/O Streams and Standard I/O Devices Variable declaration is similar to: istream cin; ostream cout; To use cin and cout, the preprocessor directive #include <iostream> must be used Input stream variables: type istream Output stream variables: type ostream cin and the Extraction Operator >> The syntax of an input statement using cin and the extraction operator >> is: The extraction operator >> is binary Left-side operand is an input stream variable Example: cin Right-side operand is a variable 7 8 No difference between a single cin with multiple variables and multiple cin statements with one variable When scanning, >> skips all whitespace Blanks and certain nonprintable characters >> distinguishes between character 2 and number 2 by the right-side operand of >> If type char or int (or double), the 2 is treated as a character or as a number 2 Entering a char value into an int or double variable causes serious errors, called input failure 9 10 When reading data into a char variable >> skips leading whitespace, finds and stores only the next character Reading stops after a single character To read data into an int or double variable >> skips leading whitespace, reads + or - sign (if any), reads the digits (including decimal) Reading stops on whitespace non-digit character 11 12 2

13 14 Using Predefined Functions in a Program Function (subprogram): set of instructions When activated, it accomplishes a task main executes when a program is run Other functions execute only when called C++ includes a wealth of functions Predefined functions are organized as a collection of libraries called header files Using Predefined Functions in a Program Header file may contain several functions To use a predefined function, you need the name of the appropriate header file You also need to know: Function name Number of parameters required Type of each parameter What the function is going to do 15 16 Using Predefined Functions in a Program pow example To use pow (power), include cmath Two numeric parameters Syntax: pow(x,y) = x y x and y are the arguments or parameters In pow(2,3), the parameters are 2 and 3 17 //Example will computer 4 to the 5th #include <iostream> #include <cmath> using namespace std; int main() { double x = 4.2511, y= 5; cout << "4 to the 5th power is: "<< pow (x,y); return 0; } 18 3

cin and the get Function The get function Inputs next character (including whitespace) Stores in memory location indicated by its argument The syntax of cin and the get function: varchar Is a char variable Is the argument (or parameter) of the function cin and the ignore Function ignore function Discards a portion of the input The syntax to use the function ignore is: intexp is an integer expression chexp is a char expression If intexp is a value m, the statement says to ignore the next m characters or all characters until the character specified by chexp 19 20 cin and the ignore Function cin.get and cin.ignore #include <iostream> // the istream cin. ignore() and cin.get() member functions using namespace std; int main (void) { char firstw, secondw; cout<<"enter your first and last names: "; firstw = cin.get(); cin.ignore(30,' '); secondw = cin.get(); cout<<"the initials letters are: "<<firstw << secondw <<endl; return 0; } 21 22 putback and peek Functions putback and peek Functions putback function Places previous character extracted by the get function from an input stream back to that stream peek function Returns next character from the input stream Does not remove the character from that stream The syntax for putback: istreamvar: an input stream variable (cin) ch is a char variable The syntax for peek: istreamvar: an input stream variable (cin) ch is a char variable 23 24 4

cin.putback #include<iostream> using namespace std; int main(){ char c; cin.get(c); cin.putback( c'); cin.get(c); cout<<"\'" << c <<"\' is put the input character.\n"; return 0; } 25 The Dot Notation Between I/O Stream Variables and I/O Functions A precaution In the statement cin.get(ch); cin and get are two separate identifiers separated by a dot Dot separates the input stream variable name from the member, or function, name In C++, dot is the member access operator 26 Input Failure Things can go wrong during execution If input data does not match corresponding variables, program may run into problems Trying to read a letter into an int or double variable will result in an input failure If an error occurs when reading data Input stream enters the fail state The clear Function Once in a fail state, all further I/O statements using that stream are ignored The program continues to execute with whatever values are stored in variables This causes incorrect results The clear function restores input stream to a working state 27 28 Output and Formatting Output setprecision Manipulator Syntax of cout when used with << Syntax: expression is evaluated value is printed manipulator is used to format the output Example: endl Outputs decimal numbers with up to n decimal places Must include the header file iomanip: #include <iomanip> 29 30 5

fixed Manipulator showpoint Manipulator fixed outputs floating-point numbers in a fixed decimal format showpoint forces output to show the decimal point and trailing zeros Example: cout << fixed; Disable by using the stream member function unsetf Example: cout.unsetf(ios::fixed); scientific manipulator: outputs floating-point numbers in scientific format Examples: cout << showpoint; cout << fixed << showpoint; 31 32 setw Outputs the value of an expression in a specified number of columns cout << setw(5) << x << endl; If number of columns exceeds the number of columns required by the expression Output of the expression is right-justified Unused columns to the left are filled with spaces Must include the header file iomanip 33 #include <iostream> #include <iomanip> using namespace std; int main() { int x = 19; int a = 345; double y = 76.384; cout << fixed << showpoint; cout << "12345678901234567890" << endl; cout << setw(5) << x << endl; cout << setw(5) << a << setw(5) << "Hi" << setw(5) << x << endl << endl; cout << setprecision(2); cout << setw(6) << a << setw(6) << y << setw(6) << x << endl; cout << setw(6) << x << setw(6) << a << setw(6) << y << endl << endl; cout << setw(5) << a << x << endl; cout << setw(2) << a << setw(4) << x << endl; return 0; } 34 Additional Output Formatting Tools Additional formatting tools that give you more control over your output: setfill manipulator left and right manipulators unsetf manipulator setfill Manipulator Output stream variables can use setfill to fill unused columns with a character Example: cout << setfill('#'); 35 36 6

left and right Manipulators left: left-justifies the output Disable left by using unsetf right: right-justifies the output 37 #include <iostream> #include <iomanip> using namespace std; int main() { int x = 15; int y = 7634; cout << fixed << showpoint; cout << "12345678901234567890" << endl; cout << setw(5) << x << setw(7) << y << setw(8) << "Warm" << endl; cout << setfill('*'); cout << setw(5) << x << setw(7) << y << setw(8) << "Warm" << endl; cout << setw(5) << x << setw(7) << setfill('#') << y << setw(8) << "Warm" << endl; cout << setw(5) << setfill('@') << x << setw(7) << setfill('#') << y << setw(8) << setfill('^') << "Warm << endl; cout << setfill(' '); cout << setw(5) << x << setw(7) << y << setw(8) << "Warm" << endl; return 0; } 38 Types of Manipulators Two types of manipulators: With parameters Without parameters Parameterized: require iomanip header setprecision, setw, and setfill Nonparameterized: require iostream header endl, fixed, showpoint, left, and flush Input/Output and the string Type An input stream variable (cin) and >> operator can read a string into a variable of the data type string Extraction operator Skips any leading whitespace characters Reading stops at a whitespace character The function getline Reads until end of the current line 39 40 Debugging: Understanding Logic Errors and Debugging with cout statements Syntax errors Reported by the compiler Logic errors Typically not caught by the compiler Spot and correct using cout statements Temporarily insert an output statement Correct problem Remove output statement File Input/Output File: area in secondary storage to hold info File I/O is a five-step process 1. Include fstream header 2. Declare file stream variables 3. Associate the file stream variables with the input/output sources 4. Use the file stream variables with >>, <<, or other input/output functions 5. Close the files 41 42 7

Summary Summary Stream: infinite sequence of characters from a source to a destination Input stream: from a source to a computer Output stream: from a computer to a destination cin: common input cout: common output To use cin and cout, include iostream header get reads data character-by-character ignore skips data in a line putback puts last character retrieved by get back to the input stream peek returns next character from input stream, but does not remove it Attempting to read invalid data into a variable causes the input stream to enter the fail state 43 44 Summary The manipulators setprecision, fixed, showpoint, setw, setfill, left, and right can be used for formatting output Include iomanip for the manipulators setprecision, setw, and setfill Header fstream contains the definitions of ifstream and ofstream 45 8