In the book [1], page 360
The code is:
#include <iostream>
#include <stdexcept>
int main()
{
std::cout << "Please, enter an integer in the range 1 to 10
(inclusive):\n";
int n = 0;
while(true) {
std::cin >> n;
if(std::cin) { // Region 1
if(1<=n && n<=10) break;
std::cout << "Sorry, " << n << " is not in the [1:10]
range; please, try again\n";
}
else if(std::cin.fail()) { // Region 2
std::cin.clear();
std::cout << "Sorry, that was not a number; please try
again\n";
for(char ch; std::cin>>ch && !isdigit(ch);)
std::cout << "repeat\n";
if(!std::cin)
throw std::runtime_error("no input");
std::cin.unget();
}
else { // Region 3
// book says here : "eof or bad: give up "
throw std::runtime_error("no input");
}
}
return 0;
}
The problem is that the region 3 will never be reached.
The negation of bool "std::cin" is the bool "std::cin.fail()", according
to ISO/IEC 14882:2011 27.5.5.4, therefore, the condition " else
if(std::cin.fail()) " is a redundancy since if the flux control goes
through the "else" of region 2 then it only has happened because
std::cin.fail() is true. The effect of this is that Region 3 will never
be reached, although the book Region3 comment: "// eof or bad: give up"(
= [c]).
Regarding the commentary [c]:
First, bad will be detected by fail(), according with ISO/IEC
14882:2011(E) 27.5.5.4.9.
Secondly, eof will cause a fail-set, because it generate a format
problem, therefore the eof will be detected also by first "if" (so
entering in the region 2).
Testing (Text inside "****" is my comment) :
debian@debian:~/principles/project2$ ./a.out
Please, enter an integer in the range 1 to 10 (inclusive):
******* HERE I PRESS CTRL+D (LINUX) TO FORCE A END OF FILE **************
Sorry, that was not a number; please try again ***** EOF ENTER
REGION 2 AS MY EXPECTATION ****
1
debian@debian:~/principles/project2$
My conclusion is that this code is confusing because the last branch
will never be accessed.
But I am just learning the C ++ language and therefore I would like to
hear the opinion of the most experienced.
For the learner any little mistake in the book is a mountain generating
doubts.
[1]
http://stroustrup.com/Programming/
ISBN 978-0-321-99278-9
Fourth Printing
Programming: Principles and Practice using C++ (Second Edition)
In respect to the group and author: I have the original book;
using here only a little portion of the book for
educational/research purposes according to fair use.