input/output stream

84
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.

Upload: kamali

Post on 13-Jan-2016

95 views

Category:

Documents


0 download

DESCRIPTION

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. Streams. A stream is a sequence of bytes. Bytes are moved from memory to devices, and vice versa. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Input/Output Stream

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

Page 2: Input/Output Stream

2

Streams

A stream is a sequence of bytes. Bytes are moved from memory to

devices, and vice versa. The stream I/O facilities convert typed

objects into sequences of characters, and vice versa.

Page 3: Input/Output Stream

3

iostream Library Header Files

<iostream.h>basic stream input and output operations

<iomanip.h>formatted I/O with parametrized stream

manipulators <fstream.h>

file processing <strstream.h>//<strstrea.h> in VC++

formatting with character arrays

Page 4: Input/Output Stream

4

I/O Class Hierarchy

ios

istream ostream

iostream

fstream

Page 5: Input/Output Stream

5

Output of Built-in Typesclass ostream : public virtual ios {...

public:ostream& operator<<(const char*);ostream& operator<<(char);ostream& operator<<(short);ostream& operator<<(int);ostream& operator<<(long);ostream& operator<<(double);...

Page 6: Input/Output Stream

6

Output of User-Defined Types

#include <iostream.h>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; }

};

Page 7: Input/Output Stream

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

Page 8: Input/Output Stream

8

The put Member Function

#include <iostream.h>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.5XXY

Result:?

Page 9: Input/Output Stream

9

The Input Stream cin

#include <iostream.h>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

Page 10: Input/Output Stream

10

Page 11: Input/Output Stream

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&);...

Page 12: Input/Output Stream

12

The istream::get functions

class istream : public virtual ios {

...

int get();

istream& get(char& c);

istream& get(char* p, int n, char=‘\n’);

...

};

Page 13: Input/Output Stream

13

returns the next input character reads white space returns EOF when end of stream is

reached

get() with no arguments

Page 14: Input/Output Stream

14

get() with no arguments

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

Page 15: Input/Output Stream

15

Page 16: Input/Output Stream

16

get(char&) with one argument

reads the next input character into the character argument

reads white space returns false when end of stream is

reached returns an istream reference

Page 17: Input/Output Stream

17

Using get(char&) to Copy

#include <iostream.h>void main(){ char ch;

while( cin.get(ch) && (ch != '\n'))cout.put(ch);

}//ex10-5.cpp

It is a test.It is a test.

Result:

Page 18: Input/Output Stream

18

The 3-argument istream::get()

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

Page 19: Input/Output Stream

19

#include <iostream.h>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

Page 20: Input/Output Stream

20

ignoreistream istream::ignore(int n=1, int delim=EOF);

skips the specified number of character the default is 1, or until the delimiter is reached, the default is EOF.

Page 21: Input/Output Stream

21

getline()#include <iostream.h>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;

}//ex10-6-2.cpp

Enter a name: John Smith

John Smith

Result:

Page 22: Input/Output Stream

22

Error Detection

#include <iostream.h> void main() {int i; float r; long n; cin >> i >> r>>n; cout<<"i = "<<i<<'\n' <<"r = "<<r<<'\n' <<"n = "<<n<<'\n' <<"cin.good()= "<<cin.good()<<'\n'; }//ex10-6-3.cpp

Page 23: Input/Output Stream

23

Page 24: Input/Output Stream

24

Page 25: Input/Output Stream

25

The io-state bitsclass ios {

//...public:

enum io_state {goodbit = 0,eofbit = 1,failbit = 2,badbit = 4

}; ...};

Page 26: Input/Output Stream

26

The rdstate() Member Function

returns the state of a stream as a set of io-state bits:

int s = cin.rdstate();

Page 27: Input/Output Stream

27

Examining the State if( s & ios::goodbit )

// last operation on cin succeededif( s & ios::badbit )

// characters from cin possibly lost if( s & ios::failbit )

// some formatting error if( s & ios::eofbit )

// reached the end of file

Page 28: Input/Output Stream

28

Input of User-Defined Typesistream& 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 => ex10-6-4.cpp

Page 29: Input/Output Stream

29

Input of User-Defined Types

void main()

{ rational r;

cin >> r;

cout << "r = " << r << '\n' ;

} //ex10-6-4.cpp

Page 30: Input/Output Stream

30

Page 31: Input/Output Stream

31

Unformatted I/O functions read

istream& istream::read(char* ptr, int n); reads into a character array the number of characters

specified by the second argument n. write

ostream& ostream::write(const char*, int ); outputs from the character array the number of bytes

specified by its second argument. gcount

int istream::gcount(); returns the number of characters read by the last

input operation

Page 32: Input/Output Stream

32

#include <iostream.h>

void main()

{ char v[20];

int n;

cin.read( v, 10);

n = cin.gcount() ;

cout <<n << endl;

cout.write( v, n);

}//ex10-6-1.cpp

1234567890101234567890

Result:

Example

Page 33: Input/Output Stream

33

The Class iosclass 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

Page 34: Input/Output Stream

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);

...

};

Page 35: Input/Output Stream

35

The fill Member function

Allows us to specify the fill character

cout.fill(‘#’);

(remains in effect until changed)

Page 36: Input/Output Stream

36

Manipulators

allows formatting operations to be inserted directly in the list of input or output operations.

#include <iostream.h>

#include <iostream.h>

void main()

{ int n, m;

cin >>dec >>n;

cin >>hex >>m;

cout<<dec << n << "; "<<m<< endl;

}//ex10-7.cpp

12 1212; 18

Result:

Page 37: Input/Output Stream

37

Standard Manipulatorsios& 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

Page 38: Input/Output Stream

38

Example#include <iostream.h>

#include <iomanip.h>

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

Page 39: Input/Output Stream

39

User-Defined Manipulators

manipulator to produce a tabostream& tab(ostream& os)

{ return os << ‘\t’ ; } produce an \n and a flush

ostream& ENDL(ostream& s)

{ return s << ‘\n’ << flush ; }

Page 40: Input/Output Stream

40

Example#include <iostream.h>#include <iomanip.h>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

Page 41: Input/Output Stream

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)

Page 42: Input/Output Stream

42

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

Page 43: Input/Output Stream

43

Page 44: Input/Output Stream

44

Other Manipulators

smanip<int> setfill(int);//set the filling ‘c’

smanip<int> setprecision(int);

//set the spaces to display

smanip<int> setw(int);

//set the spaces to display the following

...

Page 45: Input/Output Stream

45

ios Manipulator (with argument)

#include <iostream.h>#include <iomanip.h>void main(){ int x = 23;

float f = 12.345;cout <<setw(6)<<setfill('#')<< hex << x << '\n';//no dotcout << oct << x << '\n';cin >> oct >> x;cout << dec<<x<<ends;cout <<setprecision(6) << f << '\n';

//effective digits, round up}//ex10-11.cpp

Page 46: Input/Output Stream

46

Page 47: Input/Output Stream

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

Page 48: Input/Output Stream

48

showbase=0200, // show integer baseshowpoint=0400, // print trailing zerosuppercase=01000, // ‘E’ ‘X’, not ‘e’ ‘x’showpos=02000, // explicit ‘+’ for integersscientific=04000, // .dddddd Eddfixed=010000, // dddd.ddunitbuf=020000, //flush after each operat.stdio=040000 //flush after each char.

}; // ...};

Page 49: Input/Output Stream

49

Flags 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);

Page 50: Input/Output Stream

50

setf(long) and unsetf(long)

setf(long) sets the options specified by its argument, without changing any of the other options.

unsetf(long) unsets the options specified by its argument.

Page 51: Input/Output Stream

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

Page 52: Input/Output Stream

52

The precision() Member Function

specifies the floating point precision the default is 6 remains set until next call to precision

cout.precision(8);

Page 53: Input/Output Stream

53

Formatting Functions

class ios {//...

public:int width(int w);//set the width return the prev. oneint width() const;//return the current widthint precision(int);//set the new, return the old,int precision() const;//return the currentchar fill(char); //set the new char and returns the prevchar fill() const; //return the current fill character

…};

Page 54: Input/Output Stream

54

The width Member Function

Allows us to specify the minimum number of characters to be used for the next numeric or string output operations.

cout.width(5); affects only the immediate numeric or

string output. larger values will not be truncated. smaller values will be padded with the fill

characters.

Page 55: Input/Output Stream

55

Example 1#include <iostream.h> #include <iomanip.h>void main(){ float g = 1.2345678;

cout <<g <<'\n';char oldfill = cout.fill('0');int oldprecis = cout.precision(4);//four effective digitscout.width(8) cout << g << '\n';cout.fill(oldfill);cout.precision(oldprecis);cout.width(8);cout<< g << '\n';

}//ex11-12.cpp

Page 56: Input/Output Stream

56

Page 57: Input/Output Stream

57

Example 2#include <iostream.h> #include <iomanip.h>void main(){ double e = 1.234;

float f = 2.1, g = 1212.25;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

Page 58: Input/Output Stream

58

Page 59: Input/Output Stream

59

Files and Streamsclass ostream : public virtual ios { //...public:

ostream& flush();ostream& seekp(streampos);ostream& seekp(streamoff, seek_dir);streampos tellp();// ...

};

Page 60: Input/Output Stream

60

Seek Direction

class ios {//...

public:enum seek_dir {

beg=0,cur=1,end=2

};//...

};

Page 61: Input/Output Stream

61

Opening an Output File

ofstream of(“data”, ios::out); in ios::out mode the file is truncated by default, ofstream implies that the file is

opened as “out” mode. ofstream of(“data”);

Append Mode ofstream of(“data”, ios::app);

Page 62: Input/Output Stream

62

File Opening Modes ios::app //Write output to end of file ios::ate //Move to end of file. Allows

//data to be written anywhere ios::in //Open file for input ios::out //Open file for output ios::trunc //erase file contents ios::nocreate //if file does not exist, the

//operation fails ios::noreplace //if the file exists, the

operation //fails

Page 63: Input/Output Stream

63

The open Member function

An ofstream object can be created without opening a specific file:

ofstream of;

A file can be attached to an ofstream object:

of.open(“data”, ios::out);

Page 64: Input/Output Stream

64

Testing the Success of open

if ( ! of ) ...

true if failbit or badbit are set.

Possible errors: opening a non-existent file attempting to read without permission attempting to write with no disk space

Page 65: Input/Output Stream

65

The void* operator

returns 0 if badbit or failbit has been set:

ios::operator void*() const

{

return fail() ? (void *)0 : (void *) (-1) ;

}

Page 66: Input/Output Stream

66

Closing a File

A file is implicitly closed when the ofstream object is destroyed.

We can explicitly close a file by using:

of.close();

Page 67: Input/Output Stream

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();//...

};

Page 68: Input/Output Stream

68

Opening an Input File

By default files are open as “in” mode:

ifstream if(“indata”, ios::in);

ifstream if(“indata”);

Page 69: Input/Output Stream

69

The open Member Function

An ifstream object may be created without specifying a file:

ifstream if;

if.open(“indata”, ios::in);

Page 70: Input/Output Stream

70

Repositioning a File Pointer

Reposition pointer at the beginning:if.seekg(0)

Reposition to the nth byte:if.seekg(n);

Position y bytes back from endif.seekg(y, ios::end);

Position at end of file:if.seekg(0, ios::end);

Page 71: Input/Output Stream

71

tellg and tellp

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

Page 72: Input/Output Stream

72

Creating an Inventory

#include <iostream.h>#include <fstream.h>#include <stdlib.h>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!!!

Page 73: Input/Output Stream

73

Page 74: Input/Output Stream

74

Read/Print Inventory#include <iostream.h>#include <fstream.h>#include <iomanip.h>#include <stdlib.h>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

Page 75: Input/Output Stream

75

Page 76: Input/Output Stream

76

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

Page 77: Input/Output Stream

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

Page 78: Input/Output Stream

78

Page 79: Input/Output Stream

79

Processing String Streams

Supported by the class istrstream. Allows:

inputting from character arrays in memory outputting to character arrays in memory

must include the following header filesin your program: iostream.h strstream.h//strstrea.h for VC++

Page 80: Input/Output Stream

80

Types of ostrstream Objects

Dynamic:

Allocates space as need. The member function str() is used to fix its size.

Static:

The object is initialized with a fixed-size array.

Page 81: Input/Output Stream

81

A Dynamic ostrstream#include <iostream.h>

#include <strstrea.h>

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, world123goodbye

Result:

Page 82: Input/Output Stream

82

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

Page 83: Input/Output Stream

83

Page 84: Input/Output Stream

84

Reading

Readings Chapter 2 Section 2.5, Chapter 3 Sections 3.5 - 3.6