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

Similar documents
C++ Input/Output Chapter 4 Topics

Chapter 3 - Notes Input/Output

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

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

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

C++ Input/Output: Streams

Software Design & Programming I

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

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

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

Chapter 3. Numeric Types, Expressions, and Output

Definition Matching (10 Points)

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

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

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

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

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

Expressions, Input, Output and Data Type Conversions

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

Objects and streams and files CS427: Elements of Software Engineering

C++ Programming Lecture 10 File Processing

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

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

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

Lecture 3 The character, string data Types Files

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

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

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

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

Introduction to C++ (Extensions to C)

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

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

Chapter 3: Input/Output

Input and Output File (Files and Stream )

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

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

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

Engineering Problem Solving with C++, Etter/Ingber

LECTURE 02 INTRODUCTION TO C++

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

CS242 COMPUTER PROGRAMMING

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

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

Fundamentals of Programming CS-110. Lecture 2

The C++ Language. Arizona State University 1

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

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

COMP322 - Introduction to C++

Introduction to Programming EC-105. Lecture 2

Streams. Rupesh Nasre.

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

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

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

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.

BITG 1233: Introduction to C++

BITG 1113: Files and Stream LECTURE 10

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

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

COMP322 - Introduction to C++

Getting started with C++ (Part 2)

CHAPTER 3 Expressions, Functions, Output

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

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

UNIT- 3 Introduction to C++

Module C++ I/O System Basics

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

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.

Objectives. In this chapter, you will:

C++ Quick Guide. Advertisements

Chapter 2: Introduction to C++

Input/Output Streams: Customizing

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

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

CS201 Solved MCQs.

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

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

Window s Visual Studio Output

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

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

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

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

Basics of C++ C++ Overview Elements I / O Assignment and Comments Formatted Output. Dr.Hamed Bdour

by Pearson Education, Inc. All Rights Reserved. 2

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

Week 5: Files and Streams

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

Chapter 2: Basic Elements of C++

Integer Data Types. Data Type. Data Types. int, short int, long int

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

Fall 2017 CISC/CMPE320 9/27/2017

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

Setting Justification

System Design and Programming II

Chapter 14 Sequential Access Files

Transcription:

Input and Output Outline Formatting outputs String data type Interactive inputs File manipulators CS 1410 Comp Sci with C++ Input and Output 1 CS 1410 Comp Sci with C++ Input and Output 2 No I/O is built into C++ instead, a library provides input stream and output stream Keyboard fstream istream executing program fstream ostream Screen <iostream> Header File Access to a library that defines 3 objects An istream object named cin (keyboard) An ostream object named cout (screen) An ostream object named cerr (screen) 3 4 1

Output Output in computer programming means to display literal values that contain in variables either to the screen (standard output) or to a file. Appearance of the output can be controlled through the process called formatting. Output Statement cout << Expression or Manipulator; cout << Expression or Manipulator; cout << ; or cout << Expression or Manipulator << Expression or Manipulator << ; << : insertion operator or symbol cout << directs the expression after it to the screen cout<<"hello world!!! "; cout<<"the area of the triangle is << Area; CS 1410 Comp Sci with C++ Input and Output 5 CS 1410 Comp Sci with C++ Input and Output 6 Header File <iostream> for a library that defines 3 objects an istream object named cin (keyboard) an ostream object named cout (screen) an ostream object named cerr (screen) Insertion Operator (<<) the insertion operator << takes 2 operands the left operand is a stream expression, such as cout the right operand is an expression of simple type, or a string, or a manipulator CS 1410 Comp Sci with C++ Input and Output 7 CS 1410 Comp Sci with C++ Input and Output 8 2

Header File for Output Object To use output object cout the header file iostream must be included in the source program and directive using for referencing cout, i.e., #include <iostream> Example #include < iostream > /* This program computes the sum of two numbers. */ int main(void) double Number1, Number2, Sum; cout << "Enter two numbers --> "; cin >> Number1 >> Number2; Sum = Number1 + Number2; cout<< "The sum of " << Number1 << " and " << Number2 << " is "<< Sum; cin.get(); cin.get(); return 0; CS 1410 Comp Sci with C++ Input and Output 9 CS 1410 Comp Sci with C++ Input and Output 10 Output Display Manipulators manipulators are used only in input and output statements endl, fixed, showpoint, setw, and setprecision are manipulators that can be used to control output format endl is use to terminate the current output line, and create blank lines in output CS 1410 Comp Sci with C++ Input and Output 11 CS 1410 Comp Sci with C++ Input and Output 12 3

Manipulators in iostream endl: terminate the output line fixed: display in decimal point format with 6 decimal places as default --.XXXXXX showpoint: display a whole number in decimal format with 6 significant digits as default XX.XXXX X.XXXXX XXXX.XX Example #include < iostream > /* This program computes the sum and product of two numbers. */ int main(void) double Number1, Number2, Sum, Product; cout << "Enter two numbers --> "; cin >> Number1 >> Number2; Sum = Number1 + Number2; Product = Number1 * Number2; cout<< "The sum of " << Number1 << " and " << Number2 << " is "<< Sum << endl; endl manipulator cout<< "The product of " << Number1 << " and " << Number2 << " is "<< Product; cin.get(); cin.get(); return 0; CS 1410 Comp Sci with C++ Input and Output 13 CS 1410 Comp Sci with C++ Input and Output 14 Output Display with endl Output Display with showpoint #include < iostream > /* This program computes the sum and product of two numbers. */ int main(void) double Number1, Number2, Sum, Product; cout << "Enter two numbers --> "; cin >> Number1 >> Number2; Sum = Number1 + Number2; Product = Number1 * Number2; cout<<showpoint; showpoint manipulator cout<< "The sum of " << Number1 << " and " << Number2 << " is "<< Sum << endl; cout<< "The product of " << Number1 << " and " << Number2 << " is "<< Product; cin.get(); cin.get(); return 0; CS 1410 Comp Sci with C++ Input and Output 15 CS 1410 Comp Sci with C++ Input and Output 16 4

Output Display with fixed #include < iostream > /* This program computes the sum and product of two numbers. */ int main(void) double Number1, Number2, Sum, Product; cout << "Enter two numbers --> "; cin >> Number1 >> Number2; Sum = Number1 + Number2; Product = Number1 * Number2; cout<<fixed; fixed manipulator cout<< "The sum of " << Number1 << " and " << Number2 << " is "<< Sum << endl; cout<< "The product of " << Number1 << " and " << Number2 << " is "<< Product; cin.get(); cin.get(); return 0; Manipulators in iomanip setw(n) fieldwidth specification manipulator: set the width of the next value (integer, float, string) to be printed over n columns with right justification as default The header file #include <iomanip> must be inserted into the source code to use manipulator setw(n) setw(n) affects only the very next item displayed, and is useful to align columns of output CS 1410 Comp Sci with C++ Input and Output 17 CS 1410 Comp Sci with C++ Input and Output 18 Output Display with setw() #include <iomanip> #include <iostream> Position #include <string> 12345678901234567890 int main ( ) int mynumber = 123 ; int yournumber = 5 ; cout<<setw(10)<< Mine <<setw(10)<< Yours <<endl <<setw(10)<<mynumber <<setw(10)<<yournumber <<endl; return 0 ; Mine Yours 123 5 each is displayed rightjustified and each is located in a total of 10 positions Decimal Number Outputs Decimal number specification manipulator -- setprecision(n): set ALL subsequent floating-point outputs to be displayed with n decimal places of accuracy provided that fixed manipulator has been previously specified. Default is usually 6. CS 1410 Comp Sci with C++ Input and Output 19 CS 1410 Comp Sci with C++ Input and Output 20 5

iomanip Manipulators Scientific: set ALL subsequent floating point outputs to be displayed in scientific notation form. This is the default. left: set ALL subsequent outputs to leftjustified within the printing field. right: set ALL subsequent outputs to right-justified within the printing field. This is the default. Output Display with setprecision() #include <iomanip> #include <iostream> int main ( ) float mynumber = 123.4 ; float yournumber = 3.14159 ; cout<<fixed<<showpoint <<setprecision(4); cout<< Numbers are: <<endl <<setw(10)<<mynumber<<endl <<setw(10)<<yournumber <<endl; return 0 ; 12345678901234567890 Numbers are: 123.4000 3.1416 each is displayed right-justified and rounded if necessary and each is located in a total of 10 positions with 4 places after the decimal point CS 1410 Comp Sci with C++ Input and Output 21 CS 1410 Comp Sci with C++ Input and Output 22 File Manipulators Examples Header File Manipulator Argument Type Effect <iostream> endl none terminates <iostream> showpoint none <iostream> fixed none <iomanip> setw(n) int <iomanip> setprecision(n) int displays decimal point suppresses scientific notation sets fieldwidth to n positions sets precision to n digits int INum1, INum2; double DNum; INum1=123; INum2=4567; DNum=12.34; Statement Output cout<<setw(4)<<inum1 <<setw(6)<<inum2; 123 4567 cout<<setw(20)<<"number 1 is" <<setw(4)<<inum1<<'\n' <<setw(10)<<"number 2 is" <<setw(2)<<inum2; cout<<setw(5)<<dnumber<<endl <<setw(7)<<dnumber<<endl <<setw(2)<<dnumber<<endl Number 1 is 123 Number 2 is4567 12.34 12.34 12.34 CS 1410 Comp Sci with C++ Input and Output 23 CS 1410 Comp Sci with C++ Input and Output 24 6

Examples Examples double DNum1, DNum2; DNum1 = 1.23; DNum2 = 45.678; Statement cout << fixed << DNum1 << '\n' << DNum2; cout << fixed << setprecision(2) << DNum1 << '\n' << DNum2; cout << scientific << DNum1 <<'\n' << DNum2; cout << fixed << setprecision(2) << setw(7) << DNum1 << '\n' << setw(7) << DNum2; Output 1.230000 45.678000 1.23 45.68 1.230000e00 4.567800e01 1.23 45.68 int INum1, INum2; double DNum; INum1=123; INum2=4567; DNum=12.34; Statement Output cout<<setw(4)<<inum1 <<setw(6)<<left<<inum2; 1234567 cout<<setw(20)<<left<<"number 1 is" <<setw(4)<<inum1<<'\n' <<setw(10)<<"number 2 is" <<setw(2)<<inum2; Number 1 is 123 Number 2 is4567 CS 1410 Comp Sci with C++ Input and Output 25 CS 1410 Comp Sci with C++ Input and Output 26 Giving a Value to a Variable In your program you can assign(give) a value to the variable by using the assignment operator = ageofdog = 12; or by another method, such as cout << How old is your dog? ; cin >> ageofdog; >> Operator >> is called the input or extraction operator >> is a binary operator >> is left associative Expression cin >> age Statement Has value cin cin >> age >> weight; 27 28 7

Extraction Operator(>>) Variable cin is predefined to denote an input stream from the standard input device(the keyboard) The extraction operator >> called get from takes 2 operands; the left operand is a stream expression, such as cin--the right operand is a variable of simple type Operator >> attempts to extract the next item from the input stream and to store its value in the right operand variable Input Input in computer programming means to copy literal values to corresponding variables either from the keyboard or from a file. Interactive input is the input obtaining from the keyboard (standard input). 29 CS 1410 Comp Sci with C++ Input and Output 30 Input Statement cin >> Variable >> Variable >> Variable >> ; >> : extraction operator or symbol cin >> directs literal values to variables cin >> Number1; cin >> Letter1 >> Letter2 >> Amount; Header File for input Object To use input object cin the header file iostream must be included in the source prorgam and directive using for referencing cout, i.e., #include <iostream> CS 1410 Comp Sci with C++ Input and Output 31 CS 1410 Comp Sci with C++ Input and Output 32 8

Extraction Operator (>>) Variable cin is predefined to denote an input stream from the standard input device(the keyboard) The extraction operator >> called get from takes 2 operands; the left operand is a stream expression, such as cin--the right operand is a variable of simple type Operator >> attempts to extract the next item from the input stream and to store its value in the right operand variable skips over (actually reads but does not store anywhere) leading white space characters as it reads your data from the input stream (either keyboard or disk file) Whitespace Characters blanks tabs end-of-line (newline) characters The newline character is created by pressing Enter or Return at the keyboard, or by using the manipulator endl or \n in a program. 33 34 Types of Inputs char a single character int a literal-integer value -- 24, -30 float a literal-integer value or a literal-floatpoint value -- 24, 24.0, -24, 2.4e01 Example int INum1, INum2; double DNum1, DNum2; char Letter1, Letter2; Statement Input at Keyboard Content cin>>inum1>>inum2 INum1=123 >>Letter1>>Letter2; 123 4567AB INum2=4567 Letter1=A Letter2=B cin>>dnum1>>letter1 >>DNum2>>Letter2; 123.0A4567B DNum1=123.0 DNum2=4567.0 Letter1=A Letter2=B CS 1410 Comp Sci with C++ Input and Output 35 CS 1410 Comp Sci with C++ Input and Output 36 9

Reading Inputs Statement Input Content 123 4567AB\n INum1=123 cin>>inum1 123 4567AB\n INum2=4567 >>INum2 Letter1=A 123 4567AB\n >>Letter1 Letter2=B >>Letter2; 123 4567AB\n 123 4567AB\n cin>>dnum1 >>Letter1 >>DNum2 >>Letter2; 123.0A4567B\n 123.0A4567B\n 123.0A4567B\n 123.0A4567B\n 123.0A4567B\n DNum1=123.0 DNum2=4567.0 Letter1=A Letter2=B String Data Type String is a sequence of characters enclosed in double quotes A string containing no characters is a null string string is not primitive data type The header file <string> must be included in the source code Examples:, Joe Nobody, Hello C++" CS 1410 Comp Sci with C++ Input and Output 37 CS 1410 Comp Sci with C++ Input and Output 38 String Declaration string LastName; string FirstName; string Name; string Message = "Hello C++"; const string ConjugateAnd = "and"; LastName = "Nobody"; N o b o d y \n FirstName = "Joe"; J o e \n Name = First + " " + LastName; cout<<name; cin<<firstname; Example #include < iostream > #include < string > int main(void) const string Blank = " "; string LastName; string FirstName, Name; cout<<"enter your lastname --> "; cin>>lastname; cout<<"enter your firstname --> "; cin>>firstname; Name = FirstName + Blank + LastName + "."; cout<<endl<<"your name is "<<Name; cin.get(); cin.get(); return 0; CS 1410 Comp Sci with C++ Input and Output 39 CS 1410 Comp Sci with C++ Input and Output 40 10

get(), getline() -- Functions Reading Character Data with the get() function cin.get(somechar) cin.get does not skip blanks Reading entire line of input including blanks with the getline() function getline(cin, inputstring); Examples string FirsrtName, LastName, Name; char MiddleIntial; char Letter1, Letter2, Letter3; Statement Input at Keyboard Content cin>>firstname >>MiddleInitial >>LastName; getline(cin,name); cin>>letter1 >>Letter2; cin.get(letter3); Joe M Nobody\n Joe M Nobody\n Joe M Nobody\n Joe M Nobody\n Joe M Nobody\n Joe M Nobody\n A B C D\n A B C D\n A B C D\n A B C D\n FirstName=Joe MiddleInitial=M LastName=Nobody Name=Joe M Nobody Letter1=A Letter2=B Letter3= CS 1410 Comp Sci with C++ Input and Output 41 CS 1410 Comp Sci with C++ Input and Output 42 String Input Using getline string firstname; string lastname; getline(cin, firstname); getline(cin, lastname); Results Using getline string firstname; string lastname; getline(cin, firstname); getline(cin, lastname); Suppose input stream looks like this: Joe Hernandez 23 What are the string values? Joe Hernandez 23? firstname lastname 43 44 11

ignore( ) -- Function Skipping Characters with the ignore function cin.ignore(10, \n); cin.ignore(10, 'c'); The above statements skips the next 10 input characters or to skip characters until a newline character is read or a character 'c' is read. CS 1410 Comp Sci with C++ Input and Output 45 Examples Statement Input Content 123 4567 89\n INum1=123 987 65\n INum2=4567 INum3=987 123 4567 89\n cin>>inum1>>inum2; 987 65\n cin.ignore(50,\n); 123 4567 89\n 987 65\n cin>>inum3; 123 4567 89\n 987 65\n cin.ignore(4,\n); cin>>letter1 >>Letter2; cin.ignore(100,'d'); cin>>letter3, 12345ABCDEF\n 12345ABCDEF\n 12345ABCDEF\n 12345ABCDEF\n 12345ABCDEF\n 12345ABCDEF\n Letter1=5 Letter2=A Letter3=E CS 1410 Comp Sci with C++ Input and Output 46 Interactive I/O In an interactive program the user enters information while the program is executing Before the user enters data, a prompt should be provided to explain what type of information should be entered After the user enters data, the value of the data should be printed out for verification. This is called echo printing that way, the user will have the opportunity to check for erroneous data Prompting for Interactive I/O // prompt cout << Enter part number : << endl; cin >> partnumber ; // prompt cout << Enter quantity ordered : << endl; cin >> quantity; // prompt cout << Enter unit price : << endl; cin >> unitprice; // calculate totalprice = quantity * unitprice; // echo the input cout << Part # << partnumber << endl; cout << Quantity: << quantity << endl; cout << Unit Cost: $ << setprecision(2) << unitprice << endl; // output cout << Total Cost: $ << totalprice << endl; 47 48 12

Diskette Files for I/O #include <fstream> input data disk file A:\myInfile.dat your variable (of type fstream) executing program your variable (of type fstream) output data disk file A:\myOut.dat To Use Disk I/O, you must Access use #include <fstream> Choose valid identifiers for your filestreams and declare them Open the files and associate them with disk names Use your filestream identifiers in your I/O statements (using >> and <<, manipulators, get, ignore) Close the files 49 50 Files and Streams Operating files in C++ requires the following steps: 1. Including the <fstream> header file 2. Declare a file variable of type fstream that will be associated with the actual or physical file 3. Opening the file connecting the file variable to the actual file 4. Operations using the file name (i.e., read - >> and write - <<) 5. Closing the file Example Writing to a file 1. #include <fstream> 2. fstream outfile; 3. outfile.open( a:\\prog1.txt",ios::out); 4. outfile<<data; 5. outfile.close(); CS 1410 Comp Sci with C++ Input and Output 51 CS 1410 Comp Sci with C++ Input and Output 52 13

Example ios -- Arguments Reading from a file 1. #include <fstream> 2. fstream infile; 3. infile.open( a:\\prog1.txt",ios::in); 4. infile<<data; 5. infile.close(); arguments: ios::in ios::out ios::app input(already exist) output(creates a new file) append(appends to the end of existing file) CS 1410 Comp Sci with C++ Input and Output 53 CS 1410 Comp Sci with C++ Input and Output 54 Example Using Disk I/O #include <fstream> int main() fstream myinfile, myoutfile; //declarations //open file to read myinfile.open( A:\\myIn.dat,ios::in); //open file to write myoutfile.open( A:\\myOut.dat,ios::out); // close files myinfile.close( ); myoutfile.close( ); return 0; What does opening a file do? associates the C++ identifier for your file with the physical (disk) name for the file if the input file does not exist on disk, open is not successful if the output file does not exist on disk, a new file with that name is created if the output file already exists, it is erased places a file reading marker at the very beginning of the file, pointing to the first character in it 55 56 14

Stream Fail State when a stream enters the fail state, further I/O operations using that stream have no effect at all. But the computer does not automatically halt the program or give any error message possible reasons for entering fail state include: invalid input data (often the wrong type) opening an input file that doesn t exist opening an output file on a diskette that is already full or is write-protected 57 15