310 likes | 592 Views
C++ Stream Input/Output. Introduction Libraries Stream Input Precision Field Width Format Flags. C++ I/O. “type safe” Automatically adjusts to the requirements of the data type Improper data will cause a compiler error
E N D
C++ Stream Input/Output • Introduction • Libraries • Stream Input • Precision • Field Width • Format Flags
C++ I/O • “type safe” • Automatically adjusts to the requirements of the data type • Improper data will cause a compiler error • Different that C, which may process improper data with strange results
C++ I/O • Occurs in streams (a sequence) of bytes, from a device to memory or vice-versa • Low-level, high speed, high volume (unformatted) I/O capabilities by specifying the number of bytes to be transferred • Usually used between devices & memory • High-level, lower speed, smaller volume (formatted) I/O, in which bytes are grouped into integers, characters, etc. • Usually people prefer this way
Libraries • <iostream> - defines I/O functions • Instance of istream: • cin – standard input • Instances of ostream: • cout – standard output • cerr – outputs an error message • clog – buffered output • <iomanip> - for formatting • <fstream> - for file processing
Stream Input Classes & Objects • The istream class supports stream-input operations • The predefined object cin is an instance of the istream class • Connected to the standard input device (usually the keyboard) • cin >> x; //data “flows” in the directions of the arrows //to the right
Stream Output Classes & Objects • The ostream class supports stream-onput operations • The predefined object cout is an instance of the ostream class • Connected to the standard output device (usually the computer screen) • cout << x; //data “flows” in the directions of the arrows //to the left
Stream Output • Use static_cast<void*>() to output an address value (see output.txt) • Use cout.put() to output one character #include <iostream> using namespace std; int main(){ char *str = "string"; cout<<str<<endl; //string cout<<static_cast<void*>(str)<<endl; //0x10d60 cout.put('A').put('\n'); //A return 0; }
Stream Input • Stream extraction operator (>>) skips whitespace characters (such as blanks, tabs, newlines) in the input stream • Can enter any number of blanks, tabs, and newlines and this program will still work (skip.txt) #include <iostream> using namespace std; int main(){ int a, b; cout<<"Enter 2 integers: "; cin>>a>>b; cout<<"product="<<a*b<<endl; return 0; }
Stream Input • Stream extraction operator (>>) returns false (0) when end-of-file is encountered or when an error occurred (eof.txt) #include <iostream> using namespace std; int main(){ int num = 0, max = 0; cout<<cin.eof()<<endl; //0 while(cin>>num) //stops for EOF (ctrl-z, ctrl-d) if(num>max) max = num; cout<<max<<endl; cout<<cin.eof()<<endl; /*1*/ return 0; }
Stream Input • cin.get() • returns a character or EOF for end-of-file • cin.get(char ch) • stores the character in ch • returns 0 for end-of-file • cin.get(char *str, int max, char delimiter) • Reads up to max-1 characters, or until the delimiter is read • A null character is put at end of string • Delimiter remains on the input stream
Stream Input • cin.getline(char *str, int max, char delimiter) • Reads up to max-1 characters, or until the delimiter is read • A null character is put at end of string • Delimiter is removed from the input stream
Class Exercise • What’s the output, if we enter: - “this is a sentence” #include <iostream> using namespace std; int main(){ const int SIZE = 20; char buf[SIZE]; char ch; cout<<"Enter a sentence:"; ch=cin.get(); cout<<ch<<endl; cin.get(ch); cout<<ch<<endl; cin>>buf; cout<<buf<<endl; cin.get(buf,SIZE,'e'); cout<<buf<<endl; cin.getline(buf,SIZE,'\n'); cout<<buf<<endl; return 0; }
Istream Member Functions • ignore(int n) • Skips over n number of characters • putback(char ch) • Places ch back into the input stream • char peek() • Returns the next character from the input stream, but does not remove the character from the stream
Example Program #include <iostream> /*see ignore.txt*/ using namespace std; int main(){ char ch, str[10]; cout<<"enter: ";//enter: abcdefg cin.ignore(3); ch=cin.peek(); cout<<ch<<endl; //d cin.putback('A'); cin.putback('B'); ch=cin.peek(); cout<<ch<<endl; //B cin>>str; cout<<str<<endl; //BAdefg return 0; }
Unformatted I/O • Read & write member functions are used to input/output a specified number of bytes #include <iostream> /*see unfor.txt*/ using namespace std; int main(){ char str[10]; cout<<"enter: "; //enter: abcdefghijklm cin.read(str,10); cout.write(str,cin.gcount()); //abcdefghij cout<<endl; return 0; } (gcount()=# of characters read by last input operation)
Stream Manipulators • Hex, dec, or oct set the base of an integer • Can also use setbase(n), where n=16,10,8 #include <iostream> /*see hex.txt*/ #include <iomanip> using namespace std; int main(){ int x = 12; cout<<hex<<x<<" "; cout<<dec<<x<<" "; cout<<oct<<x<<" "<<endl; //c 12 14 cout<<setbase(16)<<x<<" "; cout<<setbase(10)<<x<<" "; cout<<setbase(8)<<x<<" "<<endl;//c 12 14 return 0; }
Stream Manipulators • The stream base value remains the same until changed explicitly #include <iostream> /*see hex2.txt*/ #include <iomanip> using namespace std; int main(){ int x = 12; cout<<hex<<x<<" "; cout<<x<<" "; cout<<x<<" "<<endl; //c c c cout<<setbase(10)<<x<<" "; cout<<x<<" "; cout<<x<<" "<<endl; //12 12 12 return 0; }
Floating-point Precision • Number of places past the decimal point • Use cout<<setiosflags(ios::fixed) with cout.precision(n), or cout<<setprecision(n) • N is the number of places past the decimal point • cout.precision() with no argument returns the precision setting
Output: 12.3457 12.3 12.35 12.346 12.3457 12.34567 12.3 12.35 12.346 12.3457 12.34567 5 Set Precision #include <iostream> #include <iomanip> using namespace std; int main(){ double x = 12.34567; cout<<x<<endl; cout<<setiosflags(ios::fixed); for(int i=1;i<=5;i++){ cout.precision(i); cout<<x<<endl; } for(int j=1;j<=5;j++) cout<<setprecision(j)<<x<<endl; cout<<cout.precision()<<endl; return 0; /*see setp.txt*/ }
Field Width • Number of character positions in input or output • cout.width(n) • cout<<setw(n) • N is the field width • Otherwise fill characters are inserted as padding • If the value has more character than N, the full number will be printed
Field Width /*see width.txt*/ #include <iostream> #include <iomanip> using namespace std; int main(){ cout.width(5); cout<<123<<endl; // 123 cout<<setw(5)<<123456<<endl; //123456 return 0; }
My Stream Manipulator #include <iostream> /*see my.txt*/ #include <iomanip> using namespace std; istream &george(istream &in){ in.get(); in.putback('g'); return in; } ostream &fred(ostream &out){ return out<<"Its Fred!"; } int main(){ char str[10]; cout<<"enter: "; //enter: string cin>>george>>str; cout<<str<<endl; //gtring cout<<fred<<endl; //Its Fred! return 0; }
Format Flags • Various format flags control formatting • Listed in section 21.7, p. 782 • Controlled by member functions: • cout.setf(ios::??) – set a format • cout.unsetf(ios::??) – unset a format • cout.flags(ios::??) – set format • Or by parameterized stream manipulators: • cout<<setiosflags(ios::??) – set a format • cout<<resetiosflags(ios::??) – unset a format
Format Flags • ios::right – right justification • ios::left – left justification • ios::internal • Number’s sign is left-justified • Number’s magnitude is right-justified
Format Flags • ios::scientific – scientific notation • ios::uppercase • hex numbers, e in scientific notation become uppercase • ios::showpos • show “+” for positive numbers (see format.txt)
Format Flags float originalFormat = cout.flags(); int d = 12345; cout<<setw(10)<<d<<setw(10)<<d<<endl; // 12345 12345 cout<<setiosflags(ios::left); cout<<setw(10)<<d<<setw(10)<<d<<endl; //12345 12345 cout<<setiosflags(ios::internal|ios::showpos); cout<<setw(10)<<d<<endl; //+ 12345
Format Flags cout.fill('$'); cout<<setw(10)<<d<<endl; //+$$$$12345 cout<<setfill('*')<<setw(10)<<d<<endl; //+****12345 cout<<resetiosflags(ios::showpos); cout<<setfill(' ')<<setw(10)<<d<<endl; // 12345 cout<<setiosflags(ios::showbase); cout<<hex<<12345<<endl; //0x3039 cout<<setiosflags(ios::scientific|ios::uppercase); cout<<123.456<<endl; //1.234560E+002
Boolean Format • Use stream manipulator "boolalpha" to display "bool" values as strings ("true" or "false") • Use "noboolalpha" to display as integers (0 or 1) /*see bool.txt*/ #include<iostream> using namespace std; int main(){ bool b = true; cout<<"b="<<boolalpha<<b<<endl; //b=true cout<<"b="<<noboolalpha<<b<<endl; //b=1 return 0; }
Class Exercise 2 • See exercise2.txt