--Originally published at World's Fanciest Cursors
Today’s quiz involved a bit of learning. Besides creating and executing functions we neede to check for correct user input.
The first thing checked is whether the input is actually a number and not some other kind of symbol. To do that I used some code I found that checks for input call failures here. An input call failure usually happens when you try to enter the wrong type of data to a variable, like trying to enter a letter into an “int” variable. This code checks for such a failure and evaluates to true if it exists. We can use this flag to alter the flow of execution to a loop that clears the error, skips the problem data and asks again for input.
The second thing to check is for negative numbers. As we know, negative numbers cannot be used in root operations as that would result in an imaginary number. We need to make sure the user enters positive values. This can be accomplished with a simple if statement that evaluates if the input is greater or equal to zero. If that is false we can set a loop to ask again for input over and over again until an appropriate answer is given. Learn more about operators here.
It works!:
Here, enjoy some spaghetti-code:
#include <iostream> #include <cmath> double square_root (double); double cube_root (double); int main () { double a; std::cout << "Give me a positive number and I'll get its square and cubic roots.\nEnter your number:" << std::endl; while(1) { std::cin >> a; while(1) // Loop that cheacks for wrong input types { if (std::cin.fail()) // Detects a failure of the input function { std::cin.clear(); // Clears the error std::cin.ignore(); // Continue reading "Week 3 quiz, the one about functions"