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

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

C++ Input/Output: Streams

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

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

Software Design & Programming I

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

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

Chapter 3 - Notes Input/Output

Setting Justification

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

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

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

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

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

Definition Matching (10 Points)

C++ Input/Output Chapter 4 Topics

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

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

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

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

Getting started with C++ (Part 2)

What we will learn about this week:

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

Chapter 12. Streams and File I/O

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

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

C++ Programming Lecture 10 File Processing

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

Expressions, Input, Output and Data Type Conversions

The C++ Language. ! What happens when executing the following code? int anint; Cout << "The integer is " << anint << endl;

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

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

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

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

The C++ Language. Arizona State University 1

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

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

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

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

File I/O CS 16: Solving Problems with Computers I Lecture #9

COMP322 - Introduction to C++

Introduction to C++ (Extensions to C)

Streams. Rupesh Nasre.

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

Topic 2. Big C++ by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

CS490: Problem Solving in Computer Science Lecture 3: Input/Output

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

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

COMP322 - Introduction to C++

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

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

Input/Output Streams: Customizing

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-

BITG 1233: Introduction to C++

Engineering Problem Solving with C++, Etter/Ingber

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

Chapter 12 - C++ Stream Input/Output

CS150 Intro to CS I. Fall Fall 2017 CS150 - Intro to CS I 1

Chapter 3: Input/Output

Streams - Object input and output in C++

Programming in C/C

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

Chapter 11 Customizing I/O

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

CSCI 1061U Programming Workshop 2. C++ Basics

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

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.

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

CS242 COMPUTER PROGRAMMING

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

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++

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

Chapter 11 Customizing I/O

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

CHAPTER 3 Expressions, Functions, Output

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!

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

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

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

Programming in C/C

In this chapter, you will learn about: An Array Type for Strings. The Standard string Class. Vectors. Introduction Computer Science 1 CS 23021

Copyright 2003 Pearson Education, Inc. Slide 1

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

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

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

Programming. C++ Basics

Objectives. In this chapter, you will:

Objects and streams and files CS427: Elements of Software Engineering

Chapter 11 Customizing I/O

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

Sample Code: OUTPUT Daily Highs & Lows

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Chapter 3. Numeric Types, Expressions, and Output

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

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

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

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

Transcription:

The C++ Language Input and Output Output! Output is information generated by a program.! Frequently sent the screen or a file.! An output stream is used to send information. Another type supplied by C++ Very complex, made up of several simple types. 2 1

Output to The Screen! Syntax: cout << Expression << Expression ;! The << is called the insertion operator! The value of each expression is printed to the screen from left to right.! Must include basic input/output support: #include <iostream> 3 Output to The Screen (Examples) int cost; cost = 259; cout << cost; cout << "The cost is " << cost; cout << "You need " << cost / 100 << " dollars and " << cost % 100 << " cents."; Output (for each statement) 259 The cost is 259 You need 2 dollars and 59 cents. 4 2

Output to The Screen! The output on the previous slide would really be on one line 259The cost is 259You need 2 dollars and 59 cents.! How do we force a new line to be used? 5 Output to Separate Lines! Use the endl manipulator to start new lines. Manipulators are special identifiers.! By using endl, the following output statements generate 3 lines of output cout << cost << endl; cout << "The cost is " << cost << endl; cout << "You need " << cost / 100 << " dollars and " << cost % 100 << " cents." << endl; 6 3

Debugging Tip!! When writing your programs, it's often useful to include extra output statements to print out the value of variables or other kinds of information.! Use output statements generously, but remove them before submitting your assignment for grading! 7 Formatting Output! Care is needed when displaying numbers int i,j,k; i = 15; j = 2; k = 6; cout << "Results:" << i << j << k << endl; displays Results:1526! Remember to put in spaces cout << "Results: " << i << ' ' << j << ' ' << k << endl; Results: 15 2 6 8 4

Manipulators! Manipulators are special identifiers that change the behavior of input and output.! Used frequently for formatted output! Except for endl, you must include support for manipulators #include <iomanip> cout << ExpressionOrManipulator << ExpressionOrManipulator ; 9 Displaying Decimal Points! C++ does not show a decimal point for floating point values with only 0 after the decimal.! Use the showpoint manipulator to always display the decimal point.! Use the noshowpoint manipulator to hide the decimal point again. 10 5

Formatting Numeric Output! C++ uses scientific notation to display floating point values unless told otherwise.! Use the fixed manipulator to display a fixed number of digits after the decimal. This should generally be combined with showpoint! Use the scientific manipulator to return to scientific notation 11 Formatting Numeric Output! Example const double SMALL = 0.000012345678; // using scientific notation cout << SMALL << endl; // Now use fixed point notation cout << showpoint << fixed; cout << SMALL; cout << scientific << noshowpoint; // back to default! Displays 1.23457e-005 0.000012 12 6

Formatting Numeric Output! To control The number of digits of precision in scientific notation The number of digits after the decimal in fixed point notation use the setprecision manipulator. setprecision(integerexpression) 13 Precision Example! Example const double SMALL = 0.000012345678; cout << setprecision(8); // using scientific notation cout << SMALL << endl; // Now use fixed point notation cout << showpoint << fixed; cout << SMALL;! Displays (notice the rounding on the second output) 1.2345678e-005 0.00001235 14 7

Fixed Width Output! You can force a value to take up a certain amount of space by using the setw manipulator.! Syntax:! Warnings setw(integerexpression) setw applies only to the next value printed setw does not work with string variables 15 Fixed Width Output (Examples) 16 int a, b, c; a = 10; b = 3247; c = -123; cout << setw(5) << a << b << setw(5) << c << endl; cout << setw(6) << "Year" << setw(3) << b << setw(4) << a << endl; Output 103247-123 5 5 Year3247 10 6 4 3247 is too wide, so C++ prints it out as is. 8

Fixed Width Output! C++ normally right-justifies fixed width output! Use the left manipulator to switch to leftjustified output.! Use the right manipulator to switch back. cout << left << setw(4) << 1 << 2; cout << setw(3) << 3; cout << right; cout << setw(3) << 4; 1 23 4 4 3 3 17 Fixed Width Output! Occasionally, a character other than a space is needed to fill in extra spaces in fixed width output.! Use the setfill manipulator to use a different character.! Syntax setfill(characterexpression) 18 9

Fixed Width Output (Example)! Example: Print out an integer with leading zeroes. cout << setfill('0') 0010 << setw(4) << 10 << endl; // reset fill character to a space cout << setfill(' '); 19 Escape Sequences 20! C++ uses special sequence of characters to print out some information.! Example: Print out "Hello" including the quotes cout << "\"Hello\"" << endl;! The backslash \ followed by a character is called an escape sequence. \" \\ \t \n Double quote Single backslash A tab character A new line 10

Input! Input is information that is provided to the program! Frequently from the keyboard or a file! An input stream is used to receive information Another type supplied by C++ 21 Input From the Keyboard! Syntax cin >> Variable >> Variable ;! The >> is called the extraction operator! Information is read from left to right Skips leading whitespace! Spaces, tabs, new lines, etc.! Information is stored into variables from left to right.! Must include iostream just like output to screen. 22 11

Input From the Keyboard (Example) 10.0 ab 9 100 c D 98.6 int i; string s; double d; char c; cin >> d >> s >> i; cin >> s >> c; cin >> c >> i >> s; // d is 10.0, s is "ab", i is 9 // s is "100", c is 'c' // c is 'd', i is 98, s is ".6" 23 Tracing Input! Need to track the reading marker Location of next character to read! Extraction operator skips leading whitespace Stops at last valid character for type or whitespace int i; 98 98.6 98 98.6 98 98.6 cin >> i; cin >> i; 24 12

Exercise (in class) Trace the reading marker and determine what is stored in each variable after each statement. Hello World! 212.0 95.7 93 int i; double d; string s; char c; cin >> c >> s; cin >> s >> d >> i >> c; cin >> d >> c >> i; 25 Ignoring Input! Sometimes you do not want to store information from the keyboard.! Use the cin.ignore function to ignore input.! Syntax cin.ignore( IntegerExpr, CharacterExpr );! Semantics Ignore up to IntegerExpr input characters or until CharExpr is read and discarded from the keyboard. 26 13

Ignoring Input (Examples) Hello World! 98.6 Hello World! 98.6 My name is Johnny. My name is Johnny. cin.ignore(100, '\n'); Hello World! 98.6 Hello World! 98.6 My name is Johnny. My name is Johnny. cin.ignore(10, '\n'); 27 Ignoring Input! Problem: Ignore input up to and including a specified character. #include <climits> const char DELIMITER = '['; // upper and lower bounds, // defines INT_MAX, INT_MIN // what to ignore up to 28 int main() { // Code, code, code cin.ignore(int_max, DELIMITER); // skip past DELIMITER // next character to read follows DELIMITER cin >> intgr; // more code } 14

Reading Whitespace (Single Character)! Whitespace is normally ignored by the extraction operator.! Use the cin.get function to read in a single character, whether it's a space or not.! Syntax cin.get(charvariable); 29 Reading Whitespace (Example) char ch1, ch2, ch3; A M A M A M A M cin >> ch1; cin.get(ch2); cin >> ch3; // ch1 contains 'A', ch2 contains ' ', ch3 contains 'M' 30 15

Reading Whitespace (Strings)! Strings containing white space can be read as long as there is a delimiting character.! To read from the marker to the end of line into a string, use the getline function Delimiting character is '\n', the newline character! Syntax getline(cin, StringVariable); 31 Reading Whitespace (Example) Fred Flintstone Laborer 13301 Barney Rubble Laborer 43583 string aline; getline(cin, aline); // aline now contains "Fred Flintstone\tLaborer\t13301" Fred Flintstone Laborer 13301 Barney Rubble Laborer 43583 32 16

Reading Whitespace (Strings)! Notice that the delimiting character is read, but NOT stored in the string.! A different delimiting character can be specified by using a third parameter! Syntax getline(cin, StringVariable, CharExpr); 33 Reading Whitespace (Example) Fred Flintstone Laborer 13301 Barney Rubble Laborer 43583 const char DELIMITER = '\t'; getline(cin, Name, DELIMITER); // "Fred Flintstone" getline(cin, Title, DELIMITER); // "Laborer" cin >> id; // 13301 getline(cin, Name2, DELIMITER); // What is this? 34 17

Files! A file is used to store data on a disk! Programs often need to read files for input or send output to a file! C++ provides file streams Input file streams Output file streams! Must include support for file streams #include <fstream> 35 Input File Streams! To read input from a file, first declare a variable with the type ifstream ifstream denotes input file stream! Example ifstream instream; 36 18

Input File Streams! The input file stream must be associated with a file on the disk.! To associate it with a file, it must be opened, and the name of the file specified.! Example instream.open("inputdata.txt");! The file named InputData.txt must exist and be in the same directory as your.cpp file. 37 Input File Streams! To read input from the file, use the extraction operator and other input functions we described. Replace cin with the variable name of your input stream, e.g., instream! Examples instream >> id; instream.ignore(int_max, DELIMITER); getline(instream, aline); 38 19

Input File Streams! When you are finished with the input file stream, it must be closed. Tells Windows the file is no longer in use! Example instream.close(); 39 Output File Streams! To send output to a file, first declare a variable with the type ofstream ofstream denotes output file stream! Example ofstream outstream; 40 20

Output File Streams! Just like input file streams, output file streams need to be associated with a file on your disk! To associate it with a file, it must be opened and the name of the file specified.! Example outstream.open("results.txt");! The output file is created in the same directory as your.cpp file If the output file already exists, it is replaced with new contents. 41 Output File Streams! To send output to a file, use the insertion operator and other output manipulators we described. Replace cout with the variable name of your output file stream.! Examples outstream << "Hello World!" << endl; outstream << fixed << showpoint << 0.00001 << endl; 42 21

Output File Streams! In order to guarantee that all of your output is written the file must be closed Tells Windows your program is done with the file. Just like with input file streams.! Example outstream.close(); 43 22