Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.

Slides:



Advertisements
Similar presentations
Computer Programming Basics Assistant Professor Jeon, Seokhee Assistant Professor Department of Computer Engineering, Kyung Hee University, Korea.
Advertisements

CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
File streams Chapter , ,
I/O and Program Control Statements Dick Steflik. Overloading C++ provides two types of overloading –function overloading the ability to use the same function.
Programming Stream Manipulators. COMP102 Prog. Fundamentals I: Stream Manipulator Slide 2 Stream Manipulators in iostream.h Library I/O stream manipulators.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
Input/Output Main Memory istream ostream Disk Drive Keyboard Scanner Disk Drive Monitor Printer stream = sequence of bytes.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output.
Chapter 3: Input/Output
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 27P. 1Winter Quarter I/O Manipulation Lecture.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
CSCE 121: Introduction to Program Design and Concepts J. Michael Moore Fall 2014 Set 11: More Input and Output 1 Based on slides created by Bjarne.
1 Advanced Input and Output COSC1567 C++ Programming Lecture 9.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
C++ Streams Lecture-2.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output.
TEXT FILES. CIN / COUT REVIEW  We are able to read data from the same line or multiple lines during successive calls.  Remember that the extraction.
C++ Streams Lecture-2. C++ Streams Stream  A transfer of information in the form of a sequence of bytes I/O Operations:  Input stream: A stream that.
Input/Output Sujana Jyothi C++ Workshop Day 2. C++ I/O Basics 2 I/O - Input/Output is one of the first aspects of programming that needs to be mastered:
The C++ Programming Language Streams. Contents u Output Stream u Input Stream u Formatting u Manipulators u Files & Streams.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 5: Continuing with C++ I/O Basics.
1 Simple Input/Output  C++ offers the iostream library, which defines a system of character-oriented Input/Output (I/O) using object oriented programming.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 31 Thanks for Lecture Slides: C How to Program by Paul Deital &
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1436 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah Alakeel.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
1 Today’s Objectives  Announcements Turn in Homework 4 Quiz 4 will be on Wednesday, July 19 – It will have questions about inheritance, polymorphism,
Chapter 3: Input/Output
Chapter -7 Basic function of Input/output system basics and file processing Stream classes : I/O Streams. A stream is a source or destination for collection.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
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.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
1 Manipulators manipulators are used only in input and output statements endl, fixed, showpoint, setw, and setprecision are manipulators that can be used.
Streams One of the themes of this course is that everything can be reduced to simple (and similiar) concepts. Streams are one example. Keyboard and Screen.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
Program Input and the Software Design Process ROBERT REAVES.
Input/Output. Objectives In this chapter you will: Learn what a stream is and examine input and output streams Explore how to use the input stream functions.
24 4/11/98 CSE 143 Stream I/O [Appendix C]. 25 4/11/98 Input/Output Concepts  Concepts should be review!  New syntax, but same fundamental concepts.
Chapter Expressions and Interactivity 3. The cin Object 3.1.
CS 1430: Programming in C++ 1. File Input in VS Project Properties Debugging Command Arguments quiz8-1.out We want to know how to do it ourselves, right?
CCSA 221 Programming in C INPUT AND OUTPUT OPERATIONS IN C – PART 1 1.
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.
Topic 2 Input/Output.
C++ Basic Input and Output (I/O)
Standard Input - Output
Chapter 21 - C++ Stream Input/Output
Chapter 2 part #3 C++ Input / Output
Data Streams.
Standard Input/Output Streams
Standard Input/Output Streams
Advanced Input and Output
Manipulators CSCE 121 J. Michael Moore
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Chapter 3: Input/Output
Chapter 3 Input output.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 2 part #3 C++ Input / Output
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Chapter 1 c++ structure C++ Input / Output
Introduction to Programming
Presentation transcript:

Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user –The routines are in some senses easier to use –Some aspects of the routines can be set without having to repeat them (e.g., setting the desired precision for printing floating point values) Readings: , , , ,

Outline Simple input/output (iostream.h) cout, cin, cerr output insertion operator (<<) and chaining int, float, string input extraction operator (>>) and chaining int string Advanced input/output manipulators (iomanip.h) file input/output (fstream.h) opening/closing files

Using iostream.h Include iostream.h instead of stdio.h Standard iostream objects: cout - object providing a connection to the monitor cin - object providing a connection to the keyboard cerr - object providing a connection to error streem To perform input and output we send messages to one of these objects (or one that is connected to a file)

The Insertion Operator (<<) To send output to the screen we use the insertion operator on the object cout Format: cout << Expression; The compiler figures out the type of the object and prints it out appropriately cout << 5; // Outputs 5 cout << 4.1; // Outputs 4.1 cout << “String”; // Outputs String cout << ‘\n’; // Outputs a newline

The Extraction Operator (>>) To get input from the keyboard we use the extraction operator and the object cin Format: cin >> Variable; No need for & in front of variable The compiler figures out the type of the variable and reads in the appropriate type int X; float Y; cin >> X; // Reads in an integer cin >> Y; // Reads in a float

Chaining Calls Multiple uses of the insertion and extraction operator can be chained together: cout << E1 << E2 << E3 << … ; cin >> V1 >> V2 >> V3 >> …; Equivalent to performing the set of insertion or extraction operators one at a time Example cout << “Total sales are $” << sales << ‘\n’; cin >> Sales1 >> Sales2 >> Sales3;

Setting the Width You can use the width(int) function to set the width for printing a value, but it only works for the next insertion command (more on this later): int x = 42; cout.width(5); cout << x << ‘\n’; // Outputs 42

Setting the Fill Character Use the fill(char) function to set the fill character. The character remains as the fill character until set again. int x = 42; cout.width(5); cout.fill(‘*’); cout << x << ‘\n’; // Outputs ***42

Format of Float Floating point values are printed out in fixed or scientific notation based on how they are stored/initialized: cout << 2.3; // Outputs 2.3 cout << 5.67e8; // Outputs 5.67e+08 cout << 0.0; // Outputs 0

Significant Digits in Float Use function precision(int) to set the number of significant digits printed (may convert from fixed to scientific to print): float y = ; cout.precision(1); cout << y << '\n'; // Outputs 2e+01 cout.precision(2); cout << y << '\n'; // Outputs 23 cout.precision(3); cout << y << '\n'; // Outputs 23.1

Manipulators Isn’t that all kind of involved?? –Plus, what’s that with width only counting for one arg? A solution - manipulators –A manipulator is a simple function that can be included in an insertion or extraction chain C++ manipulators –must include iomanip.h to use –several are provided to do useful things –you can also create your own (see 17.3, 17.5, 17.6, 17.8)

Output Manipulators (no args) Manipulators included like arguments in extraction endl - outputs a new line character, flushes output dec - sets int output to decimal hex - sets int output to hexadecimal oct - sets int output to octal Example: #include int x = 42; cout << oct << x << endl; // Outputs 52\n cout << hex << x << endl; // Outputs 2a\n cout << dec << x << endl; // Outputs 42\n

Output Manipulators (1 arg) Manipulators taking 1 argument setw(int) - sets the width to int value setfill(char) - sets fill char to char value setprecision(int) - sets precision to int value setbase(int) - sets int output to hex if int is 16, oct if int is 8, dec if int is 0 or 10

Input Status Flags When performing input, certain problems may occur, we can determine if an error has occurred by checking these flags: eof() - end-of-file occurred during input fail() - input operation failed good() - no flags set (not eof or any of fail flags) Flags stay set and all input fails until clear() function called

Testing Status Flags int x; int total = 0; cin >> x; while (!cin.eof()) { total += x; cin >> x; } cout << “Total is “ << total << endl;

Testing Status Flags Extraction is an operator, returns cin object (can check eof() or other flags after operation): int x; int total = 0; while (!(cin >> x).eof()) total += x; cout << “Total is “ << total << endl;

Integer Input If none of the flags hex, dec, oct set then we can indicate how an int is formatted with value typed: 42 - decimal octal 52 0x2a - hexadecimal 2a If any of these flags set, all input will be treated as being of only that type –note, in explicit decimal format, 052 read as 52, 0x2a read as 0

Character Input The extraction operator when applied to a character ignores whitespace To read any character use the get(char) function, can also provide no argument (works like getchar) char ch; cin >> ch; // Reads next non-whitespace char cin.get(ch); // Reads next character (any) while (cin.get() != ‘\n’); // Reads to newline

String Input Can use arguments of string type like any other variable –like scanf with %s reads as many chars as typed (may be too many) –can control by using width(int) function or setw(int) manipulator –ignores leading whitespace –stops at first whitespace Example char string[101]; cint >> setw(100) >> string;

String Input with Whitespace Use function get(stringloc,size,delimitchar) –reads string into array at stringloc taking in at most size chars and stopping at delimitchar (default is ‘\n’ -- you can leave delimitchar off) –stops before delimitchar Use function getline to also read newline character Example: char theline[101]; cin.get(theline,100,’\n’); // or cin.get(theline,100);

File Input/Output Done with the same operations (insertion, extraction) as keyboard input and monitor output Simply open input or output object with connection to a file and use it where you would use cin or cout To use –include –create input object of type ifstream –or output object of type ofstream

Opening Files Use open function or include file name when declaring variable: ifstream inobj1; inobj1.open(“in1.dat”) ifstream inobj2(“in2.dat”); To check if file successfully opened check object in condition: if (!inobj1) cout << “Unable to open file in1.dat” << endl;

Closing a File Use close() on object to close connection to file: ifstream in(“in.dat”); … in.close();

File Example #include void main() { char infname[101]; char outfname[101]; char buffer[101]; cout << ”File to copy from: "; cin >> infname; ifstream in(infname); if (!in) { cout << "Unable to open " << infname << endl; exit(0); }

File Example (cont) cout << "File to copy to: "; cin >> outfname; ofstream out(outfname); if (!out) { cout << "Unable to open " << outfname << " -- already exists!" << endl; exit(0); } in.getline(buffer,100); while (!in.eof()) { out << buffer << endl; in.getline(buffer,100); } in.close(); out.close(); }