Strange Output

A

arnuld

WANTED: A simple program to print out the number user entered:
PROBLEM: does not handle the invalid input



#include <iostream>

int main()
{
int i;

std::cout << "Please enter a number: ";
std::cin >> i;

std::cout << "you entered: "
<< i
<< std::endl;


return 0;
}


================= OUTPUT =====================
[arnuld@dune C++]$ g++4 -ansi -pedantic -Wall -Wextra test.cpp
[arnuld@dune C++]$ ./a.out
Please enter a number: 345
you entered: 345
[arnuld@dune C++]$ ./a.out
Please enter a number: w
you entered: 134514646
[arnuld@dune C++]$ ./a.out
Please enter a number: 1222222222222222222222222222222222
you entered: 134514646
[arnuld@dune C++]$


Now can I make this program to handle these invalid inputs, so that it
prints the message that you did not enter a number or to ask the user to
enter a small number ?
 
J

jason.cipriani

PROBLEM:  does not handle the invalid input ....
  std::cout << "Please enter a number: ";
  std::cin >> i; ....
Now can I make this program to handle these invalid inputs, so that it
prints the message that you did not enter a number or to ask the user to
enter a small number ?

The >> operator sets the fail bit of the istream when it can't parse
the input. You want to check to see if the fail bit is set after
receiving input. This will let you detect errors:

int x;
cin >> x;
if (cin.fail())
cout << "Invalid input." << endl;
else
cout << "Valid input: " << x << endl;

All istreams actually provide a ! operator that tells you if either
the fail bit or the bad bit is set, so you can use this syntax as
well:

int x;
cin >> x;
if (!cin)
cout << "Invalid input." << endl;
else
cout << "Valid input: " << x << endl;

And, since the >> operator evaluates to the istream itself, you can do
this:

int x;
if (!(cin >> x))
cout << "Invalid input." << endl;
else
cout << "Valid input: " << x << endl;

However, note that this still leaves the input on the stream,
unprocessed. You will want to read this FAQ:

http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.3

And possibly this one:

http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.4

They should answer the remainder of your questions.

HTH,
Jason
 
A

arnuld

All istreams actually provide a ! operator that tells you if either
the fail bit or the bad bit is set, so you can use this syntax as
well:

isn't that the not operator ? I mean std::istream returns 0 on fail
and 1 on success and by side-effect it takes the input.





This was exactly what I needed :) . I did not understand much of what
std::cin.ignore does:

std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');

I almost always have seen these 2 together. When .clear has already
cleared the cin (removed the invalid input) then why do we need
the .ignore thing.

2nd, numeric_limits is a function in the Std. Lib., thats all I am
able to deduce for now:

1) What does std::streamsize do and
2) what does std::cin.ignore(numeric_limits<std::streamsize::max())
does
3) what if I replace the max() with min().
 
J

jason.cipriani

isn't that the not operator ?

It's the ! operator. Operators can be overloaded with new definitions
for class types. A special ! operator is defined for istream that
evaluates to true of the fail or bad bits are set. For more
information about operator overloading in general, see:

http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.1
I mean std::istream returns 0 on fail
and 1 on success and by side-effect it takes the input.

No, std::istream does not return anything at all; it is a class not a
function. It does not make sense to say that a class "returns"
something.
     std::cin.clear();
     std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');

I almost always have seen these 2 together. When .clear has already
cleared the cin (removed the invalid input) then why do we need
the .ignore thing.

The clear() function is not for removing input. You may want to read
the istream documentation:

http://www.cplusplus.com/reference/iostream/istream/

Specificially:

http://www.cplusplus.com/reference/iostream/ios/clear.html
http://www.cplusplus.com/reference/iostream/istream/ignore.html
2nd, numeric_limits is a function in the Std. Lib., thats all I am
able to deduce for now:

 1)  What does std::streamsize do and

It's just a data type, it does nothing:

http://www.cplusplus.com/reference/iostream/streamsize.html
 2)  what does std::cin.ignore(numeric_limits<std::streamsize::max())
does

See documentation links above.
 3) what if I replace the max() with min().

What do you think? See numeric_limits documentation:

http://www.cplusplus.com/reference/std/limits/numeric_limits.html


Most of the questions you've asked here can be answered just by
finding and reading the relevant documentation. Google is a good way
to find the documentation, unless you have your own local copy that
you are referring to.

Jason
 
J

James Kanze

isn't that the not operator ? I mean std::istream returns 0 on
fail and 1 on success and by side-effect it takes the input.

It's more complex than that.

First, the streams functions aren't always very well named: fail
returns true if either failbit or badbit is set, good isn't the
opposite of bad, etc. Basically, the only one you're interested
in is fail() (until the input has failed, in which case, some of
the others can be used to determine the cause of failure). In
addition, the streams define an operator! which returns fail(),
and an implicit conversion to a pointer type which returns a nul
pointer if fail() is true, a non-nul pointer
otherwise---pointers can, of course, be used as boolean values.
(The reason for not returning a bool is that bool converts to
int, and the conversion can lead to ambiguities, or even the
wrong operator being chosen, in expressions like stream <<
object.)
This was exactly what I needed :) . I did not understand much of what
std::cin.ignore does:
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');

Here, it's being used to resynchronize input. After an error,
typically, you don't know exactly how much input has been
consumed. If, for example, you input an int, and the user has
entered "abc", nothing will have been consumed. Any time you
have an error in input, you have to resynchronize the input
somehow, skipping more or less ahead until some reasonable point
to continue. For a lot of simple syntaxes, skipping ahead until
the next line is a reasonable solution.
I almost always have seen these 2 together. When .clear has
already cleared the cin (removed the invalid input) then why
do we need the .ignore thing.

clear doesn't remove anything from the stream; it resets the
error status.
2nd, numeric_limits is a function in the Std. Lib., thats all
I am able to deduce for now:

It's basically being used here as infinity. ignore requires a
count, so we give it the largest count available.
1) What does std::streamsize do and

std::streamsize is an integral type; it's the type of ignore's
first parameter, and more general, the type used to specify how
many bytes in stream functions.
2) what does std::cin.ignore(numeric_limits<std::streamsize::max())
does

It skips all characters up until the end of file. Not very
useful. Basically, ignore is used in two ways:

input.ignore( n ) ; // skip the next n characters
input.ignore( std::numeric_limits< std::streamsize >::max(),
ch ) ; // skip through the next ch in
// the input.
3) what if I replace the max() with min().

You're requesting a negative number of characters to be skipped.
(The standard is actually a little vague about what this means,
but I'd generally expect nothing to happen.)
 
J

James Kanze

On Jan 5, 3:20 pm, "(e-mail address removed)"

[...]
Most of the questions you've asked here can be answered just
by finding and reading the relevant documentation. Google is a
good way to find the documentation, unless you have your own
local copy that you are referring to.

This is true, but finding the relevant documentation isn't
always trivial for a beginner. And Google isn't necessarily a
good solution; it will turn up lots of documentation, but not
necessarily correct documentation, and a beginner isn't really
in a position to judge it. (The links you posted do seem OK, at
least at first glance, but I've seen some horrors on the net as
well.)
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top