Reputation: 103
I don't quite understand this question. It wants me to write a code that prompts for and reads a double and repeats that process until the user has correctly entered a floating point number.
Isn't double
a type of floating point
? So how would this code end?
EDIT - Ok, so maybe the program needs to take in a double and continue doing so until the value entered is a float. This means, as long as the precision of the input is in the range of a double, but not of a float, it will continue taking input. However, if the precision of the input is within that of a float, the program ends. Does this seem correct?
Upvotes: 1
Views: 667
Reputation: 153935
When reading a formatted value fails, the stream goes into failure mode, i.e., it gets std::ios_base::failbit
set. Once it is in failure mode, the stream won't accept any further input until it's state gets clear()
ed. Once it is cleared, the bad input needs to be discarded. One way to do so is to ignore()
all characters until the end of the line. The corresponding could would look like this:
double value(0);
while (!(std::cin >> value) && !std::cin.eof()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::stremsize>::max(), '\n');
}
If the input on the given line should not contain any garbage, e.g., consider input of the format 12.3x
broken, the condition can be extended to check if there is some other character on the line:
while ((!(std::cin >> value) || std::cin.peek() != '\n') && !std::cin.eof()) {
...
}
Upvotes: 3
Reputation: 3335
If you are using boost
your function that checks the input (which is in a string) would look like this:
static bool isCorrect( const std::string& value )
{
try
{
boost::lexical_cast< double >( value ) ; /* this code only checks */
return true ;
}
catch(...)
{
std::cerr << value << " argument is not double!" << std::endl ;
return false ;
}
}
If you cannot use any other library then you need to parse string to see if the string contains digits, an optional dot, and then digits, and if your requirements ask for E type format then if it is followed by E and digits. For this you need to write a parser, and that would be the real requirement you received. This requirement is intended to teach you to write a parser rather than to deliver a code, so I will leave it for you to do.
Upvotes: 0