1 Input/Output Stream Lesson #10 Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M.

Slides:



Advertisements
Similar presentations
File streams Chapter , ,
Advertisements

 2006 Pearson Education, Inc. All rights reserved Stream Input/Output.
Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
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.
計算機概論實習 Stream Stream: sequence of bytes Input: from device (keyboard, disk drive) to memory Output: from memory to device (monitor, printer,
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 11 Chapter 21 - C++ Stream Input/Output Outline 21.1Introduction.
Chapter 3: Input/Output
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Outline 21.1Introduction 21.2Streams Iostream Library Header.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 27P. 1Winter Quarter I/O Manipulation Lecture.
Unformatted and Formatted I/O Operations. 2 Unformatted Input/output is the most basic form of input/output. Unformatted I/O transfers the internal binary.
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.
C++ Programming Certificate University of Washington Cliff Green
1 Advanced Input and Output COSC1567 C++ Programming Lecture 9.
CHAPTER 3 INPUT/OUTPUT. In this chapter, you will:  Learn what a stream is and examine input and output streams  Explore how to read data from the standard.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
Object Oriented Programming in C++ Chapter 11 STL.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
C++ Streams Lecture-2.
1 Streams 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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005.
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.
C++ Programming: chapter 6 – iostream 2014, Spring Pusan National University Ki-Joune Li 1.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 11- C++ Stream Input/Output Outline 11.1Introduction 11.2Streams Iostream Library Header.
Lecture Contents I/O Streams. –Input/output streams. –Unformatted vs formatted streams. –Stream manipulators. –Stream error state. –Stream tying. –Examples.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
Student Book Input / Output in C++
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:
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.
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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
1 Today’s Objectives  Announcements Turn in Homework 4 Quiz 4 will be on Wednesday, July 19 – It will have questions about inheritance, polymorphism,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Streams, and File I/O Review. STREAMS Review STREAMS Streams are sequences of bytes. C++ I/0 occurs in streams Input – bytes flow from device to memory.
#include int main() { char *string1=”C++”; char *string2=”Program”; int m=strlen(string1); int n=strlen(string2); for(int i=1;i
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.
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.
C++ Programming: chapter 6 – iostream 2015, Spring Pusan National University Ki-Joune Li 1.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
C++ How to Program, 8/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 13 Stream Input/Output C++ How to Program, 9/e © Copyright 2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Streams & Files in C++:Stream Classes, stream errors, disk file I/O with streams, File Pointers, Error handling in file I/O, File I/O with member functions,
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.
CS212: Object Oriented Analysis and Design
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
Chapter 21 - C++ Stream Input/Output Stream Manipulators
Output Stream Formatting
Chapter 21 - C++ Stream Input/Output
CPSC 231 D.H. C++ File Processing
Standard Input/Output Streams
Standard Input/Output Streams
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.
Chapter 13: Advanced File and I/O Operations
Topics Input and Output Streams More Detailed Error Testing
Chapter 12 - C++ Stream Input/Output
Chapter 12: Advanced File Operations.
Chapter 4 INPUT AND OUTPUT OBJECTS
C++ Stream Input/Output
C++ Programming: chapter 6 – iostream
Chapter 12 - C++ Stream Input/Output
C++ Programming Lecture 8 File Processing
Input/Output Streams, Part 2
Presentation transcript:

1 Input/Output Stream Lesson #10 Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek

2 Streams u A stream is a sequence of bytes. u Bytes are moved from memory to devices, and vice versa. u The stream I/O facilities convert typed objects into sequences of characters, and vice versa.

3 iostream Library Header Files u basic stream input and output operations u formatted I/O with parametrized stream manipulators u file processing u // in VC++ formatting with character arrays

4 I/O Class Hierarchy ios istreamostream iostream fstream

5 Output of Built-in Types class ostream : public virtual ios {... public: ostream& operator<<(const char*); ostream& operator<<(char); ostream& operator<<(short); ostream& operator<<(int); ostream& operator<<(long); ostream& operator<<(double);...

6 Output of User-Defined Types #include class rational { int num, den; public: rational(int n=0, int d=1) { num=n; den = d; } int get_num() { return num; } int get_den() { return den; } };

7 Output of User-Defined Types ostream& operator<<(ostream& os, rational r) {os << '(' << r.get_num() <<',' << r.get_den() <<')'; return os; } void main() {rational r(3, 10); cout << "r = " << r << '\n' ; }//ex10-1.cpp, output: r = (3,10) Overloading the operator<<!!!

8 The put Member Function #include void main() {int n = 26; float f = 5.0 / 2.0; cout << n <<"; "<<f<<endl; char c ='X' ; cout.put(c); cout.put(c).put('Y').put('\n') ; }//ex10-2.cpp 26; 2.5 XXY Result:?

9 The Input Stream cin #include void main() {int a, b; float r; char ch; cout <<"input two integers, one float and a character: \n"; cin >> a >> b >> r >> ch; cout <<"a= " << a << ", b= " << b << '\n' ; cout <<"r= " << r << ", ch= " << ch << '\n' ; }//ex10-3.cpp

10

11 Input of Built-in Types class istream : public virtual ios { //... public: istream& operator>>(char *); istream& operator>>(char&); istream& operator>>(short&); istream& operator>>(int&); istream& operator>>(long&); istream& operator>>(float&);...

12 The istream::get functions class istream : public virtual ios {... int get(); istream& get(char& c); istream& get(char* p, int n, char=‘\n’);... };

13 u returns the next input character u reads white space u returns EOF when end of stream is reached get() with no arguments

14 get() with no arguments u #include u int main() u {char name[80]; u char ch = '\0'; u int i = 0; u cout << "Enter your name: "; u while(1) u { ch = cin.get(); u if( ch == '\n') break; u cout.put(ch); u name[i++] = ch; u } u name[i] = '\0'; u cout <<'\n'<< name<<'\n'; u return 0; u }//ex10-4.cpp

15

16 get(char&) with one argument u reads the next input character into the character argument u reads white space u returns false when end of stream is reached u returns an istream reference

17 Using get(char&) to Copy #include void main() {char ch; while( cin.get(ch) && (ch != '\n')) cout.put(ch); }//ex10-5.cpp It is a test. Result:

18 The 3-argument istream::get() u istream & get (char * buf, int len, char delim = ‘\n’) u reads at most (len-1) characters u stores input into a vector of characters(buf) u stores the null character at the end u stops reading when delimiter is encountered u delimiter will be the next character to read

19 #include main() {char name[30]; while(1) {cout << “Enter a name:”; cin.get(name, 30, ‘\n’); //cin.get(name, 30); if (cin.get(ch) && ch == ‘\n’) break; else { cout << “excess input!”<<endl; cin.ignore(1000, ‘\n’); } cout <<name<<endl; } }//ex10-6.cpp

20 u ignore u istream istream::ignore(int n=1, int delim=EOF); u skips the specified number of character the default is 1, or until the delimiter is reached, the default is EOF.

21 getline() #include void main() {char name[30], ch; while(1) {cout << "Enter a name:"; cin.getline(name, 30); if (cin.get(ch) && ch == '\n') break; else {cout << "excess input!"<<endl; cin.ignore(100, '\n'); } cout << name<<endl; }//ex cpp Enter a name: John Smith John Smith Result:

22 Error Detection u #include u void main() u {int i; u float r; u long n; u cin >> i >> r>>n; u cout<<"i = "<<i<<'\n' u <<"r = "<<r<<'\n' u <<"n = "<<n<<'\n' u <<"cin.good()= "<<cin.good()<<'\n'; u }//ex cpp

23

24

25 The io-state bits class ios { //... public: enum io_state { goodbit = 0, eofbit = 1, failbit = 2, badbit = 4 };... };

26 The rdstate() Member Function u returns the state of a stream as a set of io-state bits: int s = cin.rdstate();

27 Examining the State u if( s & ios::goodbit ) // last operation on cin succeeded if( s & ios::badbit ) // characters from cin possibly lost u if( s & ios::failbit ) // some formatting error if( s & ios::eofbit ) // reached the end of file

28 Input of User-Defined Types istream& operator>>(istream& s, rational & r) {/* allow only input of the form: (n) or (n,d)*/ int n=0, d=1; char c; s >> c; if ( c == '(' ) {s >> n >> c; if (c == ',') s >> d >> c; if ( c == ')') r =rational(n,d); } else s.putback(c); return s; }//add this to ex10-1.cpp => ex cpp

29 Input of User-Defined Types void main() {rational r; cin >> r; cout << "r = " << r << '\n' ; } //ex cpp

30

31 Unformatted I/O functions u read u istream& istream::read(char* ptr, int n); u reads into a character array the number of characters specified by the second argument n. u write u ostream& ostream::write(const char*, int ); u outputs from the character array the number of bytes specified by its second argument. u gcount u int istream::gcount(); u returns the number of characters read by the last input operation

32 #include void main() {char v[20]; int n; cin.read( v, 10); n = cin.gcount() ; cout <<n << endl; cout.write( v, n); }//ex cpp Result: Example

33 The Class ios class ios {... public: ostream* tie(ostream* s);//set the stream tied ostream* tie();//get the stream tied long flags(long f);//set the new, return the prev. long flags() const;//return the current flag

34 long setf(long setbits, long field);//set flags in a //particular field and return the old long setf(long);//set one or more flags, return the old long unsetf(long);//clear one or more flags, return old int rdstate() const;//get the state of the stream int eof() const;//check reaching the end of the stream int fail() const; int bad() const; int good() const; void clear()(int i=0);... };

35 The fill Member function u Allows us to specify the fill character cout.fill(‘#’); (remains in effect until changed)

36 Manipulators u allows formatting operations to be inserted directly in the list of input or output operations. #include void main() {int n, m; cin >>dec >>n; cin >>hex >>m; cout<<dec << n << "; "<<m<< endl; }//ex10-7.cpp 12 12; 18 Result:

37 Standard Manipulators ios& oct(ios&);//output in octal ios& dec(ios&);//output in decimal ios& hex(ios&);//outpur in hexadecimal ostream& endl(ostream&); //add a ’\n’ and flush ostream& ends(ostream&); //add a ’ ’ and flush ostream& flush(ostream&);// output the buffer istream& ws(istream&);// ignore the space

38 Example #include void main() { int j = 200; cout << " " << '\n' <<setw(5)<<1<< '\n' <<2 << '\n' <<setw(6)<<3<< '\n' << setfill('*') << setw(10) << j << '\n' << setw(6) << j +1 << endl; } //ex10-8.cpp

39 User-Defined Manipulators u manipulator to produce a tab ostream& tab(ostream& os) {return os << ‘\t’ ;} u produce an \n and a flush ostream& ENDL(ostream& s) {return s << ‘\n’ << flush ; }

40 Example #include ostream& tab(ostream& os) {return os << '\t';}; ostream& ENDL(ostream& s){return s << ‘\n’ << flush ; } void main() {int A = 65, B = 42; char x[20]; cout <<A << ',' <<oct <<A << ',‘ <<hex <<A << ',' <<B << ',‘ <<dec <<B << ','<<endl; cin >> ws >> x; cout << tab <<"x = "<< tab << x << ENDL; }//ex10-9.cpp

41 How Does it Work? class ostream : public virtual ios {//... public: ostream& operator<<(ostream& (*f)(ostream &)) {return (*f)(*this);} //... }; ostream& tab(ostream& os) {return os << '\t';}; ostream& ENDL(ostream& s){return s << ‘\n’ << flush ; } cout <<tab <<ENDL; //… cout.operator<<(tab).operator <<(ENDL) //tab(cout) ENDL(cout)

42 Example #include void main() { float x = ; cout.width(8); cout.fill('*'); cout.setf(ios::left, ios::adjustfield); cout <<"x = " << x <<endl; cout.setf(ios::scientific, ios::floatfield); cout << <<endl; cout.precision(7); cout << <<'\n'; } //ex10-10.cpp

43

44 Other Manipulators smanip setfill(int);//set the filling ‘c’ smanip setprecision(int); //set the spaces to display smanip setw(int); //set the spaces to display the following...

45 ios Manipulator (with argument) #include void main() {int x = 23; float f = ; cout <<setw(6)<<setfill('#')<< hex << x << '\n';//no dot cout << oct << x << '\n'; cin >> oct >> x; cout << dec<<x<<ends; cout <<setprecision(6) << f << '\n'; //effective digits, round up }//ex10-11.cpp

46

47 Format State class ios { public: enum { skipws=01, //skip white space on input left=02, // padding after value right=04, // padding before value internal=010, //padding between sign/value dec=020, // decimal oct=040, // octal hex=0100, //hexadecimal

48 showbase=0200,// show integer base showpoint=0400,// print trailing zeros uppercase=01000,// ‘E’ ‘X’, not ‘e’ ‘x’ showpos=02000,// explicit ‘+’ for integers scientific=04000,//.dddddd Edd fixed=010000,// dddd.dd unitbuf=020000,//flush after each operat. stdio=040000//flush after each char. }; //... };

49 Flags u A set of formatting instructions using the function flags(). int options= ios::right | ios::hex | ios::fixed; cout.flags(options );// saving options and setting a new one int old_opt = cout.flags(new_opt); // changing one option without affecting others cout.flags(cout.flags() | ios::showpos ); // restoring old options cout.flags(old_opt);

50 setf(long) and unsetf(long) u setf(long) sets the options specified by its argument, without changing any of the other options. u unsetf(long) unsets the options specified by its argument.

51 The setf(long, long) Function cout.setf(ios::oct, ios::basefield); cout.setf(ios::dec, ios::basefield); cout.setf(ios::hex, ios::basefield); cout.setf(ios::left, ios::adjustfield); cout.setf(ios::right, ios::adjustfield); cout.setf(ios::internal, ios::adjustfield); cout.setf(ios::scientific, ios::floatfield); cout.setf(ios::fixed, ios::floatfield); cout.setf( 0, ios::floatfield); // default

52 The precision() Member Function u specifies the floating point precision u the default is 6 u remains set until next call to precision cout.precision(8);

53 Formatting Functions class ios { //... public: int width(int w);//set the width return the prev. one int width() const;//return the current width int precision(int);//set the new, return the old, int precision() const;//return the current char fill(char); //set the new char and returns the prev char fill() const; //return the current fill character … };

54 The width Member Function u Allows us to specify the minimum number of characters to be used for the next numeric or string output operations. cout.width(5); u affects only the immediate numeric or string output. u larger values will not be truncated. u smaller values will be padded with the fill characters.

55 Example 1 #include void main() {float g = ; cout <<g <<'\n'; char oldfill = cout.fill('0'); int oldprecis = cout.precision(4);//four effective digits cout.width(8) cout << g << '\n'; cout.fill(oldfill); cout.precision(oldprecis); cout.width(8); cout<< g << '\n'; }//ex11-12.cpp

56

57 Example 2 #include void main() { double e = 1.234; float f = 2.1, g = ; char ch = 'a'; cout.setf(ios::fixed|ios::showpoint); cout <<setfill('*')<<setprecision(4)<<setw(10)<<f<<'\n'; int options= ios::right | ios::hex | ios::fixed, i = 22; cout.flags(options); cout <<setw(6)<<i<<endl; }//ex11-13.cpp

58

59 Files and Streams class ostream : public virtual ios { //... public: ostream& flush(); ostream& seekp(streampos); ostream& seekp(streamoff, seek_dir); streampos tellp(); //... };

60 Seek Direction class ios { //... public: enum seek_dir { beg=0, cur=1, end=2 }; //... };

61 Opening an Output File u ofstream of(“data”, ios::out); u in ios::out mode the file is truncated u by default, ofstream implies that the file is opened as “out” mode. u ofstream of(“data”); u Append Mode u ofstream of(“data”, ios::app);

62 File Opening Modes u ios::app//Write output to end of file u ios::ate//Move to end of file. Allows //data to be written anywhere u ios::in//Open file for input u ios::out//Open file for output u ios::trunc//erase file contents u ios::nocreate//if file does not exist, the //operation fails u ios::noreplace//if the file exists, the operation //fails

63 The open Member function u An ofstream object can be created without opening a specific file: ofstream of; u A file can be attached to an ofstream object: of.open(“data”, ios::out);

64 Testing the Success of open u if ( ! of )... true if failbit or badbit are set. u Possible errors: u opening a non-existent file u attempting to read without permission u attempting to write with no disk space

65 The void* operator u returns 0 if badbit or failbit has been set: ios::operator void*() const { return fail() ? (void *)0 : (void *) (-1) ; }

66 Closing a File u A file is implicitly closed when the ofstream object is destroyed. u We can explicitly close a file by using: of.close();

67 Members of istream class istream : public virtual ios { //... public: int peek(); istream& putback(char c); istream& seekg(streampos); istream& seekg(streamoff, seek_dir); streampos tellg(); //... };

68 Opening an Input File u By default files are open as “in” mode: ifstream if(“indata”, ios::in); ifstream if(“indata”);

69 The open Member Function u An ifstream object may be created without specifying a file: ifstream if; if.open(“indata”, ios::in);

70 Repositioning a File Pointer u Reposition pointer at the beginning: if.seekg(0) u Reposition to the nth byte: if.seekg(n); u Position y bytes back from end if.seekg(y, ios::end); u Position at end of file: if.seekg(0, ios::end);

71 tellg and tellp u tellg() and tellp() return the current pointer position:  long pos = if. tellg();// Gets the value for the //stream's get pointer.  long pos = if. tellp();// Gets the value for the stream's put pointer

72 Creating an Inventory #include void main() { char name[10]; int quantity; ofstream outf("inventory", ios::out); if( !outf ) { cerr << "Cannot open file\n"; exit(1); } cout << "Enter item name and quantity: " << endl; while( cin >> name >> quantity) outf << name << ' ' << quantity << endl; }//ex10-inventory.cpp ^z to end!!!

73

74 Read/Print Inventory #include void main() { char name[10]; int quantity; ifstream inf("inventory", ios::in); if( !inf ) { cerr << "Cannot open file\n";exit(1); } while( inf >> name >> quantity) cout << setiosflags(ios::left) << setw(10) << name << setiosflags(ios::right) << setw(7) << quantity << endl; }//ex10-rpinve.cpp

75

76 Query Inventory #include void main() { char name[10]; int quantity; char item[10]; ifstream inf("inventory", ios::in); if( !inf ) {cerr << "Cannot open file\n"; exit(1); }

77 Query Inventory cout << "item name:"; cin >> item; inf >> name >> quantity; while( !inf.eof() ) { if( !strcmp(name, item) ) cout << setiosflags(ios::left) << setw(10) << name << setiosflags(ios::right) << setw(7) << quantity << endl; inf >> name >> quantity; } }//ex10-queryinv.cpp

78

79 Processing String Streams u Supported by the class istrstream. u Allows: u inputting from character arrays in memory u outputting to character arrays in memory u must include the following header filesin your program: u iostream.h u strstream.h//strstrea.h for VC++

80 Types of ostrstream Objects u Dynamic: Allocates space as need. The member function str() is used to fix its size. u Static: The object is initialized with a fixed-size array.

81 A Dynamic ostrstream #include void main() {ostrstream s; char* s1 = "Hello, world"; s << s1 << 123 << '\n'; s << "goodbye\n" << ends; char* string = s.str(); cout << string; }//ex10-dyn.cpp Hello, world123 goodbye Result:

82 A Static ostrstream u #include u void main() u { const int size=6; u int x=12345; u char buf[size]; u ostrstream s(buf, size, ios::out); u s << "x = " << x << ends; u cout << "buf contains: " << buf << endl; u }//ex10-static.cpp

83

84 Reading u Readings u Chapter 2 Section 2.5, u Chapter 3 Sections