For: COP 3330. Object Oriented Programming (Using C++)
For: COP 3330. Object Oriented Programming (Using C++)
Piyush Kumar
Example Example
Namespaces: They provide
a way to avoid name collision.
Be careful about using this. Ostream object named cout.
#include <iostream> #include <iostream>
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.
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)
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.
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
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;
4
istream member function: get
istream member function: get get (array_name, max_size) ;
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.
}
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
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
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.
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
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.
Read value(s)
user types data at keyboard
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);
} }
Control structures
11