Making an input stream fail.

J

Jason Heyes

I have a function whose job is to read a non-negative integer. Is this the
right way to do it?

std::istream &read_integer(std::istream &is, int &i)
{
if (!(is >> i) || i < 0)
is.setstate(is.failbit);
return is;
}

Any help is appreciated.
 
R

Rolf Magnus

Jason said:
I have a function whose job is to read a non-negative integer. Is this the
right way to do it?

std::istream &read_integer(std::istream &is, int &i)
{
if (!(is >> i) || i < 0)
is.setstate(is.failbit);
return is;
}

Any help is appreciated.

What about:

std::istream &read_integer(std::istream &is, unsigned int &i)
{
return is >> i;
}
 

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

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,967
Members
47,516
Latest member
ChrisHibbs

Latest Threads

Top