Ch 10. Input/Output1 Ch. 10 Input/Output Oregon State University Timothy Budd.

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

Dale Roberts Basic I/O – scanf() CSCI 230 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Department of.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
. Plab – Tirgul 8 I/O streams Example: string class.
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
Input/Output Main Memory istream ostream Disk Drive Keyboard Scanner Disk Drive Monitor Printer stream = sequence of bytes.
1 CSE1301 Computer Programming: Lecture 9 Input/Output.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Chapter 3: Input/Output
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.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
Chapter 11 Customizing I/O Bjarne Stroustrup
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
Case Study - Fractions Timothy Budd Oregon State University.
Chapter 10C++ for Java Programmers1 Chapter 10 Input/Output.
File I/O ifstreams and ofstreams Sections 11.1 &
1 CS161 Introduction to Computer Science Topic #13.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
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.
Fundamental File Processing Operations C++
1 Simple Input/Output  C++ offers the iostream library, which defines a system of character-oriented Input/Output (I/O) using object oriented programming.
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.
1 I/O  C++ has no built-in support for input/output input/output is a library (iostream)  C++ program views input and output as a stream of bytes  Input:
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
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.
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
CSE1301 Computer Programming: Lecture 6 Input/Output.
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.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Characters and Strings Functions.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
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.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
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.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3: Expressions and Interactivity.
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.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
CS212: Object Oriented Analysis and Design
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ (Extensions to C)
Chapter 1.2 Introduction to C++ Programming
Chapter 18 I/O in C.
Chapter 2 part #3 C++ Input / Output
CSI 121 Structured Programming Language Lecture 7: Input/Output
Standard Input/Output Streams
Standard Input/Output Streams
Lecture 13 Input/Output Files.
File I/O Streams, files, strings 1 1.
Today’s Lecture I/O Streams Tools for File I/O
Standard Input/Output Stream
Chapter 3 Input output.
Introduction to C++ Programming
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 2 part #3 C++ Input / Output
Today’s Objectives 28-Jun-2006 Announcements
ENERGY 211 / CME 211 Lecture 9 October 10, 2008.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
File I/O.
Input/Output Streams, Part 1
Introduction to Programming
Presentation transcript:

Ch 10. Input/Output1 Ch. 10 Input/Output Oregon State University Timothy Budd

Ch 10. Input/Output2 Introduction Two competing I/O systems in C++. –Standard I/O Library, stdio –Stream I/O Library, iostream Never use both Library in the same program.

Ch 10. Input/Output3 The stdio Library Inherited from the C. Widely known and available. Based on stable and well-exercised libraries. Not as extendable or adaptable as the newer Stream I/O Library. For developing new programs, the Stream I/O Library is preferred.

Ch 10. Input/Output4 Examples of stdio # include int c = getchar(); // read a single input character putchar('x'); // print a single character char * text = "please enter your name:"; puts(text); // print the text string char buffer[120]; gets(buffer); // read a line of input FILE * fp = fopen("mydata.dat", "r"); if (fp == NULL) puts("file cannot be opened"); fputc('z', fp); // write character to fp int c = fgetc(fp); // read character from fp char * msg = "unrecoverable program error"; fputs(msg, stderr); // write message to standard error output

Ch 10. Input/Output5 Formatted Output The printf facility works only for formatted primitive values, such as integers and floats. Not easily extendable to user-defined data types. Always verify that formatting commands match the argument types.

Ch 10. Input/Output6 Examples of Formatted Output %dinteger decimal value %ointeger printed as octal %xinteger printed as hexadecimal %cinteger printed as character %uunsigned integer decimal value %ffloating point value %gfloating point value %snull terminated string value %percent sign

Ch 10. Input/Output7 int i = 3; int j = 7; double d = i / (double) j; printf("the value of %d over %d is %g", i, j, d); char * fileName =...; if (fopen(fileName, "r") == null) fprintf(stderr,"Cannot open file %s\n", fileName); char buffer[180]; sprintf(buffer, "the value is %d\n", sum); double d = 23.5; printf("the value is %d\n", d); // error -- float printed as int scanf("%d %f", &i, &f); // read an int, then a float

Ch 10. Input/Output8 The Stream I/O Facility Whenever possible use the Stream I/O Library rather than the Standard I/O Library. Use the ability to overload function names in C++. Better possibilities for extendability as well as improved error detection.

Ch 10. Input/Output9 Figure 10.2 Various Overloading Versions of the << Operator ostream & operator << (ostream & out, const int value) { // print signed integer values on a stream unsigned int usvalue; if (value < 0) { // print leading minus sign out << '-'; usvalue = - value; }else usvalue = value; // print non-negative number out << usvalue; return out; }

Ch 10. Input/Output10 inline char digitCharacter(unsigned int value) { // convert non-negative integer digit into printable digit // assume value is less than nine return value + '0'; } ostream & operator << (ostream & out, const unsigned int value) { // print unsigned integer values on a stream if (value < 10) out << digitCharacter(value); else { out << (value / 10);// recursive call out << digitCharacter(value % 10); // print single char } return out; }

Ch 10. Input/Output11 Examples of Stream I/O # include cout << "n " << n << " m " << m << " average " << (n+m)/2.0 << '\n'; Easy to provide formatting capabilities for a new data type. ostream & operator << (ostream & out, const rational & value) { // print representation of rational number on an output stream out << value.numerator() << '/' << value.denominator(); return out; } rational frac(3,4); cout << "fraction of " << 3 << " and " << 4 << " is “ << frac << endl;

Ch 10. Input/Output12 Another Examples A manipulator is used to change features of the I/O system. ostream & endl (ostream & out) { // write the end of line character out << '\n'; // then flush the buffer out.fflush(); // then return the buffer return out; } ostream & operator << (ostream & out, ostream & (*fun)(ostream &)) { // simply execute function return fun (out); }

Ch 10. Input/Output13 Stream Input Stream input always ignores white space. cin >> intval; while (cin >> intval) { // process intval... } // reach this point on end of input... Visualize >> and << as arrows –Input operator, >> x : points data into x –Output operator, << x : copies data out of x

Ch 10. Input/Output14 String Streams A string stream writes to or reads from a string. Must include the sstream header file. ostringstream creates an output stream. Values are buffered in an internal string and can be accessed with the member function str. Useful for formatting complex output; not only perform catenation, but also automatically convert the right argument from numerous primitive data types into character values. Can be used as the string catenation operator + commonly used in Java

Ch 10. Input/Output15 # include int n =...; int m =...; ostringstream formatter; formatter << "the average of " << n << " and " << m << " is " << ((n + m)/2.0); string s = formatter.str(); string text = "Isn't this a wonderful feature"; istringstream breaker(text); string word; while (breaker >> word) cout << word << endl; // print each word on a separate line

Ch 10. Input/Output16 File Streams A file stream is a stream that reads from or writes to a file. Must include the header file # include fstream header file includes the iostream header, so not necessary to include both. The class ifstream and ofstream are used to creat streams that are attached to input and output files.

Ch 10. Input/Output17 A conversion operator changes a file stream into a boolean value, whereby the value indicates the success or failure of the file opening operation. char fileName = "outfile.dat"; ofstream ofd(fileName); // create file for output if (! ofd) { cerr << " cannot open file " << fileName } else { ofd << "first line in file"... } File operations in C++ throw far fewer exceptions than do in Java.

Ch 10. Input/Output18 An Example Program # include int main() { int wordCount = 0; double totalWordLen = 0; double totalSenCount = 0; string word; while (cin >> word) { int wordLen = word.length(); wordCount++; if (word[wordLen-1] == '.') { totalWordLen += (wordLen-1); totalSenCount++; } else { totalWordLen += wordLen; } }

Ch 10. Input/Output19 cout 0) cout << "average word length " << totalWordLen / wordCount << endl; cout << "total number of sentences " << totalSenCount << endl; if (totalSenCount > 0) cout << "average sentence length " << wordCount / totalSenCount << endl; return 0; }