I/O exceptions weirdness

A

Amadeus W.M.

I'm trying to read a list, and watch against failures with try/catch.
The code below reads a list of numbers from stdin. I input the numbers in
several ways:

1) a.out # then enter 1 2 3 4 5 Ctrl-D manually.
2) echo "1 2 3 4 5" | a.out
3) cat listfile | a.out
4) a.out < listfile

In each case an exception is thrown.

Is this normal behavior? Can anyone elaborate? It happens with
gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7) and
gcc version 3.4.0 (Red Hat Linux 3.4.0-1)


Thanks!


#include <iostream>
#include <cstdlib>
#include <list>

using namespace std;


void print_state(ios_base::iostate & s)
{
cerr << "g: " << (s & ios_base::goodbit ? 1 : 0) << " "
<< "b: " << (s & ios_base::badbit ? 1 : 0) << " "
<< "f: " << (s & ios_base::failbit ? 1 : 0) << " "
<< "e: " << (s & ios_base::eofbit ? 1 : 0) << endl;
}


int main(int argc, char * argv[])
{
double xtmp;
list<double> x;

try{

print_state(cin.exceptions());
cin.exceptions(ios_base::badbit | ios_base::failbit);

while(cin>>xtmp) x.push_back(xtmp);

}
catch(ios_base::failure & err){
print_state(cin.exceptions());
}

return 0;
}
 
R

Rob Williscroft

Amadeus W.M. wrote in in comp.lang.c++:
I'm trying to read a list, and watch against failures with try/catch.
The code below reads a list of numbers from stdin. I input the numbers
in several ways:

1) a.out # then enter 1 2 3 4 5 Ctrl-D manually.
2) echo "1 2 3 4 5" | a.out
3) cat listfile | a.out
4) a.out < listfile

In each case an exception is thrown.

You get what you ask for.
Is this normal behavior? Can anyone elaborate? It happens with
Yep.

gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7) and
gcc version 3.4.0 (Red Hat Linux 3.4.0-1)
cin.exceptions(ios_base::badbit | ios_base::failbit);

The above tells cin to raise an exception when either badbit or
failbit is set.
while(cin>>xtmp) x.push_back(xtmp);

The while will never fail as when cin>>xtmp fail's an exception is
raised (due to failbit being set) and caught below.
}
catch(ios_base::failure & err){
print_state(cin.exceptions());
}

HTH.

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top