Well from the code you've shown here,
mark
is an integer.
Regardless of the fact that an integer can only contain a number, you're still doing your error checking incorrectly. In fact, there is none.
The stream contains a number of error state flags which tell you when it has failed and offer some information regarding why it has failed. If the user inputs letters, for instance, then the stream will enter a failed state which
must be cleared before you use the stream again.
You should check those flags and handle any errors.
There are four:
std::ios_base::goodbit
,
std::ios_base::failbit
,
std::ios_base::badbit
,
std::ios_base::eofbit
.
You can find more information about them here:
http://en.cppreference.com/w/cpp/io/ios_base/iostate
There is also an "exception mask", which causes exceptions to be thrown when a certain error bit would be set instead. These are unset by default on all streams, but I usually set the exception mask to cause an exception to be thrown on an "irrecoverable stream error" by writing (for
std::cin
)
std::cin.exceptions (std::ios_base::badbit);
. See
http://en.cppreference.com/w/cpp/io/basic_ios/exceptions .
If you want to repeatedly prompt the user, then you can perform the read in a
for
loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int mark = 0;
while (! std::cin >> mark) {
/* Check to see why the stream failed: */
if (std::cin.rdstate() & std::ios_base::badbit) {
/* Irrecoverable stream error (permissions? lost connection?) */
} if (std::cin.rdstate () & std::ios_base::eofbit) {
/* There's no more input waiting for you. */
} if (std::cin.rdstate () & std::ios_base::failbit) {
/* The extraction failed. Probably the user input garbage (letters?). */
}
/* Clear the error state, then flush any garbage waiting in the stream.
Now you can the stream again. */
std::cin.clear ();
std::cin.ignore (std::numeric_limits <std::streamsize>::max ());
}
|
You should add error checking to your program. Don't just let your program crash, please.