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.

Slides:



Advertisements
Similar presentations
Chapter 10.
Advertisements

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.
File I/O Supplemental Material. Background In C++, files can be manipulated in the same manner we manipulate streams such as: cout and cin. Therefore,
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
1 File I/O In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
Streams, Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output.
Program Input and the Software Design Process ROBERT REAVES.
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.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
Chapter 8 Data File Basics.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
C++ Lecture 8 Monday, 25 August I/O, File, and Preprocessing l An in-depth review of stream input/output l File handling in C++ l C++ preprocessing.
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
Programming Principles II Lecture Notes 7 Files Andreas Savva.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Monday, Mar 31, 2003Kate Gregory with material from Deitel and Deitel Week 12 Labs 4 and 5 are back File IO Looking ahead to the final.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
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.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
1 Simple File I/O Chapter 11 Switch Statement Chapter 12.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Chapter 15 Strings as Character Arrays
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
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.
Declaring fstream Objects An istream object named cin connects program and keyboard An ostream object named cout connects the program and the screen These.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Learners Support Publications Working with Files.
CSCI 333 Data Structures I/O with C++ 20 October, 2003.
Lecture 14 Arguments, Classes and Files. Arguments.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
File I/O. Files allow permanent storage of programs and data. ifstream and ofstream objects –For file I/O the inclusion of is required. –Objects for file.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
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?
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
Chapter 1.2 Introduction to C++ Programming
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Standard Input/Output Streams
Standard Input/Output Streams
Topics Input and Output Streams More Detailed Error Testing
String What it is Why it’s useful
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
CPS120: Introduction to Computer Science
File I/O in C++ II.
Chapter 1 c++ structure C++ Input / Output
Presentation transcript:

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 operator >> with cin Use the insertion operator << with cout We will see later that cin and cout are actually objects

CMSC 2023 Using cin integers and floats cin >> i1 >> f1; // skips over whitespace characters cin >> ch1 >> ch2; // skips over whitespace To not skip whitespace, use cin.get: ch = cin.get(); // reads any character

CMSC 2024 Using cin (con’t) strings (char*) cin >> str; // reads until first whitespace Better to use cin.getline: cin.getline(str, buffer_size, end_char); where buffer_size = size of str, including ‘\0’ end_char = character to stop at Reading stops when end_char is encountered, the end-of-file is encountered, or when buffer_size-1 has been exceeded. ‘\n’ is the default for end_char. Automatically appends ‘\n’ to the string.

CMSC 2025 Using cout integers and floats cout << i1 << f1; // displayed in default format characters cout << ch; // single character displayed strings (char*) cout << str; // displays up to ‘\0’ character

CMSC 2026 General File I/O Steps Declare a file name variable Associate the file name variable with the disk file name Open the file Use the file Close the file

CMSC 2027 C++ File I/O Declare a file name variable #include ifstream input_filename_var; // input file ofstream output_filename_var; // output file

CMSC 2028 C++ File I/O (con’t) Associate the file name variable with the disk file name and open it input_filename_var.open(“pathname/filename”, ios::in); output_filename_var.open(“pathname/filename”, ios::out); where ios::in and ios::out are optional Files may be opened in other modes such as ios::app (append) and ios::binary (binary input or output)

CMSC 2029 C++ File I/O (con’t) File name declaration and opening/association may be combined: ifstream input_filename_var(pathname/filename, ios::in); ofstream input_filename_var(pathname/filename, ios::out); where ios::in and ios::out are optional

CMSC C++ File I/O (con’t) Use the file Use an input file as you would use the cin input stream ifile1 >> x >> y; // x and y are integers ifile2 >> ch; // ch is a char ch = ifile3.get(); // ch is a char ifile4.getline(buffer, buffer_size) // buffer is char*

CMSC C++ File I/O (con’t) Use an output file as you would use the cout output stream ofile1 << x << y; // x and y are integers ofile2 << ch; // ch is a char ofile3 << “Hi there!” << endl; // literal string ofile4 << str; // str is a char*

CMSC C++ File I/O (con’t) Close the file input_filename_var.close(); output_filename_var.close(); All files are closed automatically upon termination of program execution, but it is a good habit to close them explicitly. Also, close them as soon as they are no longer needed by the program.

CMSC Checking That Files Have Opened Successfully Always check that all files (input or output) have been successfully opened If any file cannot be opened, send a message to the user and terminate program execution ifstream myFile(“inputData”); if (!myFile) { cerr << “Input file could not be opened” << endl; exit(1); // must #include to use exit function }

CMSC Checking for End-of-File ifstream inFile(“somefile.txt”);... if (inFile)... OR while (inFile)... Checks to see if the last operation on inFile was successful. If yes, then the condition is true; otherwise, it is false. So, if the last operation was a read, then you are checking to see if the end-of-file has been reached.

CMSC Sample Program Using File I/O #include void main() { ifstream inFile(“numbers.dat”); int x; if (!inFile) { cerr << “Cannot open input file. Exiting.” << endl; exit(1); }

CMSC Sample Program (con’t) inFile >> x; while (inFile) { // OR while (inFile >> x) and inFile >> x; // omit the priming read cout << x << endl; } inFile.close(); }

CMSC Passing by Reference In C: swap(&x, &y); // call passes addresses void swap(int* x, int* y) { // ptrs receive addresses int temp; temp = *x; // dereference pointer *x = *y; // dereference pointers *y = temp; // dereference pointer }

CMSC Passing by Reference (con’t) In C++: swap(x, y); // just pass variable void swap(int& x, int&y) { // x and y are references int temp; temp = x; // no dereferencing x = y; // no dereferencing y = temp; // no dereferencing }

CMSC Constants #define PI 3.14 Preprocessor replaces all occurrences of PI with the value #define actually defines a macro. const int PI = 3.14; Is not replaced by the processor. Value cannot be changed -- runtime error.

CMSC Other C++ Topics Can us endl in place of ‘\n’ Variables can be declared anywhere in C++ code (but pick a logical place) Output can be formatted by using stream manipulators (e.g., setw, setprecision) (Ch. 11.6) Namespaces - now part of ANSI C++ (Ch. 21)

CMSC Other Things to be Aware of (both C and C++) in-line functions avoids a function call by “advising” the compiler to generate a copy of the function in place of each call faster execution, but larger object file inline float area(int h, int w) { return h * w} int main()...

CMSC Other Things to be Aware of (both C and C++) (con’t) static storage class scope block function file class (C++ only)