CS253

CS253: Software Development with C++

Spring 2017

I Ostreams

See this page as a slide show

CS253 I/O Streams

Predefined Streams

There are four predefined streams. Don’t open or close them. Just use them.

cerr is unbuffered, clog is buffered. Use cerr for error messages, clog if you use standard error for logging purposes.

Formatted output:

The insertion operator, <<, is used for output. You may recognize it as the left shift operator. It’s that, too. Isn’t operator overloading wonderful?

int i=5<<4;
double d=4.5;
char c='x';
const char *ccs = "My dog";
string s=" has fleas";

cout << i << ' ' << d << " " << c << "\n"
     << ccs << s << '\n';
80 4.5 x
My dog has fleas

How can you tell if << means bit shift or insertion?

endl demonstration

static int zero = 0;
cout << "Alpha" << '\n' << 1/zero << '\n';
SIGFPE: Floating point exception


static int zero = 0;
cout << "Beta" << '\n';
cout << 1/zero << '\n';
SIGFPE: Floating point exception


static int zero = 0;
cout << "Gamma" << endl;
cout << 1/zero << '\n';
Gamma
SIGFPE: Floating point exception


static int zero = 0;
cout << "Delta" << endl << 1/zero << '\n';
Delta
SIGFPE: Floating point exception

endl

cout << "alpha\n";
cout << "beta" << endl;
cout << "gamma" << "\n";
cout << "delta" << '\n';
alpha
beta
gamma
delta

Some C++ programmers think that endl and \n are synonymous. They are not.

\n means: Insert a newline ('\n') into the output stream.

endl means: Insert a newline ('\n') into the output stream, and flush the output buffer.

Don’t use endl unless you really want to flush the output buffers at that point. It’s not free.

Formatted input

The extraction operator, >>, is used for input. You may recognize it as the right shift operator. It’s that, too. Isn’t operator overloading wonderful?

    int i;
    cin >> i;		    // attempt to read an integer
    if (cin)		    // Is the stream in a happy state?
        cout << "Read i=" << i << '\n';

-or-

    int i;
    if (!cin >> i)	    // Could we read?
        cerr << "Input failed!\n";

Chaining

Input may be chained, just like output:

    int a, b, c;
    if ((cin>>a) && (cin>>b) && (cin>>c))
        cout << "a=" << a << " b=" << b << " c=" << c << '\n';

-or-

    int a, b, c;
    if (cin >> a >> b >> c)
        cout << "a=" << a << " b=" << b << " c=" << c << '\n';

The && forces left-to-right evaluation, so the numbers are read in the proper order.

Read a line

Extracting a string via >> only reads a whitespace-delimited string, which is rarely useful.

To read an entire line, use getline():

    string line;
    while (getline(cin, line))
        cout << "Input line is: " << line << '\n';

Read a character

Extracting a char via >> only reads a whitespace-delimited character, which is rarely useful. That is, it skips whitespace.

To read a raw char, without skipping whitespace, use get():

    char c;
    while (cin.get(c))
        cout << "Input character is: '" << line << "'\n";

Unlike getline in the previous slide, get is a method.

Stream state

Misuse of eof

This code is executed with no input,
yet it seems to read stuff.

while (!cin.eof()) {
    char c = 'X';
    cin.get(c);
    cout << "Read '" << c << "'\n";
}
Read 'X'


while (!cin.eof()) {
    string line = "bogus";
    getline(cin, line);
    cout << "Read '" << line << "'\n";
}
Read ''

while (!cin.eof()) {
    int n = 42;
    cin >> n;
    cout << "Read " << n << "\n";
}
Read 42

Don’t do this:

    int n;
    while (!cin.eof()) {		// BAD CODE!
        cin >> n;
        ...
    }

The better way to do it

Here’s a better way to do it:

    int n;

    while (cin >> n) {
        ...
    }

Now with error checking!

    int n;

    while (cin >> n) {
        ...
    }

    if (!cin.eof())
        cerr << "Read failed, but not at eof.  Must be non-numeric data.\n";

File streams

To read a file, create an ifstream object, and treat it like an input stream.

ifstream in("/etc/resolv.conf");
if (!in) {
    cerr << "Can’t open /etc/resolv.conf\n";
    exit(1);
}
string line;
while (getline(in, line))
    cout << "Read: " << line << '\n';
Read: search cs.colostate edu colostate.edu
Read: nameserver 129.82.45.181
Read: nameserver 129.82.103.78
Read: nameserver 129.82.103.79

Modified: 2017-01-31T09:56

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building