0% found this document useful (0 votes)
14 views11 pages

For: COP 3330. Object Oriented Programming (Using C++)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views11 pages

For: COP 3330. Object Oriented Programming (Using C++)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

C++ IO

C++ IO  All I/O is in essence, done one


character at a time

 Concept: I/O operations act on


For : COP 3330.
streams (sequences) of ASCII
Object oriented Programming (Using C++)
characters
http://www.compgeom.com/~piyush/teach/3330

Piyush Kumar

C++ IO Interactive I/O

 cout standard output stream #include <iostream>


sequence of characters printed
to the monitor output data
input data
 cin standard input stream executing
Keyboard Screen
sequence of characters input program
from the keyboard

 both cout and cin are data objects cin cout


and are defined as classes
( type istream ) ( type ostream )
class class

Example Example
Namespaces: They provide
a way to avoid name collision.
Be careful about using this. Ostream object named cout.
#include <iostream> #include <iostream>

using namespace std; Standard IO library using namespace std;


for C++. Defines two
int main(void){ fundamental types, int main(void){
istream and ostream.
cout << “Hello World” ; cout << “Hello World” ;
cout << endl; cout << endl;
return 0; return 0;
Equivalent to:
} } operator<< (cout, “Hello World”);
Its calling a friend function of
Stream: A flow of characters (1 or 2 bytes long). Can flow in and out of ostream with input data.
Files, strings, etc.
Uses function declaration (approx):
ostream& operator<<( ostream&, const char * )

1
Example invokes a manipulator function called endl.
endl looks something like this: Special Output Characters
ostream& endl( ostream& os)
{
#include <iostream> os << '\n'; \n new line
os.flush();
using namespace std; return os; \t tab
}
int main(void){ \b backspace
cout << endl; \r carriage return
return 0; Equivalent Compiler statement:
std::cout.operator<<( \ʹ single quote
} std::endl(std::cout)
); \ʺ double quote
Scope Operator for \\ backslash
namespaces.

Stream IO headers A Stream

 iostream -- contains basic information  A flow of characters.


required for all stream I/O operations
 Buffers: IO to streams goes thru a
 iomanip – used for performing formatted I/O
buffer. C++ allows you change the
with stream manipulators
default behavior of associated buffers.
 fstream – used for performing file I/O
operations  State: Each stream is associated with

 stringtream -- used for performing in- a state indicating various things like if
memory I/O operations (i.e., into or from an error has occurred or not…
strings in memory)

C++ IO Class hierarchy C++ IO Class hierarchy


ios ios

istream ostream streambuf istream ostream streambuf


cin cout

ifstream istringstream ostringstream ofstream ifstream istringstream ostringstream ofstream

stringbuf stringbuf

filebuf filebuf

2
C++ IO Hierarchy Other Predefined Streams

 The ios hierarchy defines the  cerr - the standard destination for
interface of the IO system. error messages (often the terminal
 The streambuf hierarchy defines the window). Output through this stream
implementation of the IO system, is unit-buffered, which means that
mostly provides the facilities of characters are flushed after each
buffering and byte-level I/O block of characters is sent.
 clog - like cerr, but its output is
buffered.

Formatting with predefined


Stream IO
streams.
Inside ios

 Remember: Due to inheritance,  << (left-shift operator)


anything you learn about formatting IO  Overloaded as stream insertion
with predefined streams (cin, cout, operator
clog, cerr) also applies to file IO and  >> (right-shift operator)
string IO.  Overloaded as stream extraction
 Anything available or defined in the
operator
ios class is available everywhere in  Both operators used with cin, cout,
the IO subsystem. cerr, clog, and with user-defined
stream objects

Example << operator

 cin >> Variable;  << is overloaded to work on built-in


 cout << Variable; types of C++.
 clog << Variable;  Can also be used to output user-
 Buffered defined types.
 cerr << Variable;  Other interesting examples:
 Unbuffered, prints Variable  cout << ‘\n’; // newline.
immediately.  cout << “1+2=” << (1+2) << endl;
cout << endl; // newline.
 Note: Variable types are available to 
cout << flush; // flush the buffer.
the compiler.

3
<< operator Stream insertion: One char.
 Associates from left to right, and returns a reference to  put member function
its left-operand object (i.e. cout). This enables
cascading.  Outputs one character to specified stream
 Outputs “char *” type as a string. cout.put(‘C');
 If you want to print the address, typecast it to (void *).  Returns a reference to the object that called
 Example: it, so may be cascaded
 char name[] = “cop3330”; cout.put( ‘C' ).put( '\n' );
 cout << name << static_cast<void *>( name ) << endl;  May be called with an ASCII-valued
 static_cast<void *>( name ) equivalent to ((void *) expression
name) in C except that it happens at compile time.
cout.put( 65 );
• Outputs A

Input Stream Input Stream : Looping


 >> (stream-extraction) while (cin >> fname)
 Used to perform stream input
 Normally ignores whitespaces (spaces, tabs,
newlines)
 Returns zero (false) when EOF is encountered,
otherwise returns reference to the object from which it “>>” returns 0 (false) when EOF
was invoked (i.e. cin)
• This enables cascaded input
encountered and loop terminates.
cin >> x >> y;

 >> controls the state bits of the stream


 failbit set if wrong type of data input
 badbit set if the operation fails

Example Program Output


#include <iostream>

using std::cout;
using std::cin; $ ./a.exe
using std::endl; Enter the heights: (enter end of file to end): 72
89
int main(void) { 54
int height = 0, maxheight = 0; 33
68
cout << "Enter the heights: (enter end of file to end): "; 66
while(cin >> height) Tallest person's height = 89
if( height > maxheight)
maxheight = height;

cout << "Tallest person's height = "


<< maxheight << endl;
return 0;
}

4
istream member function: get
istream member function: get get (array_name, max_size) ;

 char ch = cin.get(); char fname[256]


 Inputs a character from stream (even cin.get (fname, 256);
white spaces) and returns it.
 Read in up to 255 characters and inserts
a null at the end of the string “fname". If
 cin.get( c );
a delimiter is found, the read terminates.
 Inputs a character from stream and The array acts like a buffer. The
stores it in c delimiter is not stored in the array, but is
left in the stream.

istream member function:


istream member functions:
getline (array_name, max_size)
ignore()
char fname[256]  cin.ignore ( ) ;
cin.getline (fname, 256);  Discards one character from the input
stream.
 Same as get, except that getline  cin.ignore (10) ;
discards the delimiter from the stream.  Discards 10 characters.
 cin.ignore(256,’\n’);
 Discards 256 characters or newline,
whichever comes first.

istream member functions:


FILE IO Example.
peek(), putback()
Copy File “first.txt” into “second.txt”.

 char ch = cin.peek ( ) ; #include <iostream>


#include <fstream>
 Peeks into the stream’s next
character. using namespace std;

 cin.putback (‘A’) ; int main(void)


{
 Puts ‘A’ back in the stream. ifstream source("first.txt");
ofstream destin("second.txt");

char ch;
while (source.get(ch))
destin<<ch;
return 0;
}

5
Slightly modified More IO functions
#include <iostream>
#include <fstream>
 read()
using namespace std;
 cin.read(fname, 255);
int main(void) • Reads 255 characters from the input
{ stream. Does not append ‘\0’.
ifstream source("first.txt");
ofstream destin("second.txt");  cout.write(fname,255);
char ch; • Writes 255 characters.
while (source.peek() != EOF){
source.get(ch);
 gcount: returns the total number of
destin.put(ch); characters read in the last input
}
return 0;
operation.
}

C++ IO Class Hierarchy


Another example
Revisited #include <iostream>
ios #include <sstream>
#include <string> What if I replace this
with istringstream?

istream ostream
cin cout using namespace std;

int main() {
ifstream ofstream int i;
string line;
while(getline(cin,line)){
istringstream ostringstream stringstream sfstream(line);
iostream while (sfstream >> i){
cout << i << endl;
}
}
return 0;
}
stringstream fstream

stringstream operations
#include <iomanip>

 stringstream strm;
Stream
 stringstream strm(mystring);
 Initializes strm with a copy of mystring.
Manipulators
 strm.str();
 Returns the content of strm in string format.

 strm.str(s);
 Copies the string s into strm. Returns void.

6
dec, hex, oct, setbase Formatting Output - Integers

 oct, hex, dec  int numstdts = 35533;


 Cout << hex << 15; cout << “FSU has" << numstdts
• Prints ‘F’ << "students."
 cout << setbase(16) << 15; prints
 Prints ‘F’ again. FSU has35533students.

 default field width == minimum required


default: what happens when explicit
formatting is not specified

Formatting Output - Integers Formatting Output - Integers


p.2 p.3
 we can specify the field width, or number  cout << “FSU has" << setw(10)
of spaces used to print a value << numstdts << " students."
prints
cout << “FSU has" << setw(6) FSU has 35533 students.
<< numstdts << " students."
prints prints in field width 10, right-justified
FSU has 35533 students.
function call

prints in field width 6, right-justified

Formatting Output - Integers Using the default - Integers p.5


p.4  Note on field widths: if a field width specified is
too small, or is not specified, it is automatically
 cout << left; // flip to left justification expanded to minimum required

cout << “FSU has " << setw(10)  numstdts = 100;


cout << “FSU has "
<< numstdts << "students."
<< numstdts << " students."
prints prints
FSU has 35533 students.
FSU has 100 students.
prints in field width 10, left-justified
and works for any value of numstdts

7
Formatting Output - Reals
General Rule of Thumb
 float cost = 5.50;
 When you are printing numeric values in cout << "Cost is $" << cost
sentences or after a verbal label, the default << "today."
field width usually works well prints
Cost is $5.5today.
 When you are printing numeric values lined
up in columns in a table, it is usually
necessary to call setw to generate well-
 default
formatted output (we will see examples of  large values printed in scientific notation
this later in the course)  if number is whole, no decimal point
 numbers of digits not under your control

Formatting Output - Reals p.2 Formatting Output - Reals p.3


 Setting up real formatting

// use fixed point notation  float cost = 5.50;


cout << fixed; cout << "Cost is $" << setw(5)
<< setprecision(2) << cost
<< " today."
// print a decimal point (with whole numbers) prints
cout << showpoint; ( noshowpoint ) Cost is $ 5.50 today.

these remain in effect until changed explicity, as  if no field width is specified, minimum is used,
does setprecision. setw only changes next value just as for integers
printed.

Formatting Output - char


You can just do this, once:
 default field width == 1
 cout << fixed << showpoint note: setw does have effect on
<< setprecision(2); char type data too.

and these settings will remain in effect char ch = 'Q';


throughout your program run cout << '*' << ch << setw(3) << '*';

prints
*Q *

8
Formatting Output - Strings Useful Output Spacer
 default field width == number of  const string BLANK = " ";
characters in the string
cout << setw(10) << BLANK;
can use setw prints 10 blanks

cout << setw(10) << "Hello";  consider this:


prints const char BLANK = ' ';
Hello cout << setw(10) << BLANK;
prints 10 blanks!

Unitbuf manipulator Example Quiz


A. 0.1, 1, 1.23457e+009
#include <iostream> B. 0.100000, 1.000000, 1234567936.000000
 If you want to flush every output #include <iomanip> C. 1.000000e-001, 1.000000e+000, 1.234568e+009
D. 0.100, 1.000, 1234567936.000
using namespace std;
 cout << unitbuf E. 0.10000000000000000555
int main() {
<< “first” const double tenth = 0.1;
const float one = 1.0;
<< “second” const float big = 1234567890.0;
cout << "A. " << tenth << ", " << one << ", " << big << endl;
<< nounitbuf; cout << "B. " << fixed << tenth << ", " << one << ", " << big << endl;
cout << "C. " << scientific << tenth << ", " << one << ", " << big << endl;
cout << "D. " << fixed << setprecision(3) << tenth << ", " << one << ", " << big << endl;
cout << "E. " << setprecision(20) << tenth << endl;
return 0;
}

Manipulators: Rolling your own.


Copy not allowed
•How to create our own stream

Stream Error States


An Example. on ostreams.
manipulators?
bell
#include <iostream>
ret (carriage return)
#include <ostream>
tab
endLine
using namespace std;

ostream& myendl( ostream& os) {


os << "test\n";
os.flush();
return os;
}

int main(void) {
cout << myendl;
return 0;
}

9
Error states Error States Example
 strm::eofbit int ival;
 if (cin.eof() == true) break; // stream end of file.
 strm::failbit while ( cin >> ival, !cin.eof() ){
 if ( cin.fail() == true) break; // stream format error. Assert( !cin.bad() , “IO stream corrupted”);
if (cin.fail()){ //bad input
 strm::badbit cerr << “Bad data, try again.”;
 If (cin.bad() == true) break; // data lost! cin.clear(istream::failbit); // reset the stream
 Goodbit? continue;
 cin.good() = ((!eofbit) && (!failbit) && (!badbit))
}
// ok to process ival now
 All eofbit, failbit and badbit should be false.
} //end of while.
 cin.clear() // makes cin good.

Operators for testing. Interactive Input

 operator!  Write a prompt


• Returns true if badbit or failbit set make it friendly and informative

 Useful for file processing prompt typically contains prefix


• if ( ! readmefile ) cerr << “Error”; character to signal point at which to
enter input

 Read value(s)
user types data at keyboard

Interactive Input: Contents of


Interactive Input: Example
Output Window
int num;
char response; prefix Enter a number -> 17<return>
cout << "Enter a number -> ";
cin >> num;
Enter Y or N -> Y<return>
cout << "Enter Y or N -> ";
cin >> response;
the program will not process the
input until the return key is struck

10
Another C++ Program
Arguments: Count, Vector
(Hello argv[1])
#include <iostream>
#include <iostream>
int main(int argc, char** argv) { #include <stdlib.h>
std::cout << “Argument Count: " << argc << std::endl; using namespace std;
// Print Argument Vector int main(int argc, char *argv[]) {
for (int i = 0; i < argc; ++i) { if (argc != 2) {
std::cout << argv[i] << std::endl; cout << "Usage: hi.exe <name>" << endl;
} exit (1);
} }

cout << "Hello " << argv[1] << endl;


return 0;
}

Control structures

 Statements you should already know :


 While
 For
 If

Recommended Assignments: 1.17, 1.25

11

You might also like