I'm working on a fibonacci sequence program, and so far I have it working, but have a few extras I need to add before I'm finished. Here is what I currently have.
#include <iostream>
#include <sys/time.h>
#include <cstdlib>
#include <cmath>
usingnamespace std;
staticint fib_iter(unsignedlong n)
{
if (n == 0) return 0;
if (n == 1) return 1;
unsignedlong prevPrev = 0;
unsignedlong prev = 1;
unsignedlong result = 0;
for (int i = 2; i <= n; i++)
{
result = prev + prevPrev;
prevPrev = prev;
prev = result;
}
cout << "The fibonacci number at " << n << " is " << result << ".\n";
if (n > 93)
cout << "Warning, number too high. Overflow!\n";
}
int main() {
struct timeval stop, start;
int n;
cout << "Please enter the n value: ";
cin >> n;
while (n<0){
cout << "That isnt a positive number! \nPlease enter the n value: ";
cin >> n;
}
gettimeofday(&start, NULL);
fib_iter(n); // Calling the function
gettimeofday(&stop, NULL);
cout << "Time: " << stop.tv_usec - start.tv_usec << endl;
return 0;
}
So far I have two conditions. The first is that if the user gives a negative number, it will make them continue until the number is not negative. The second is if the user gives a number higher than the program can calculate, it will warn them about the overflow.
However, I need to make it so that if the user inputs a letter or something that isn't a number, it gives an error. How do I do this? I don't know how to make the program read if the input is a number. Also I want to be able to use a continue loop, but I want to do it as the user inputting y, Y, n, or N, and anything else will produce an error. I know how to do a continue loop using 0 or 1, but not a letter.
EDIT: Whoops, that's for if you get input as a string, but you put it directly into an int.
For that, you could check if cin encountered any problems using cin.fail.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <limits> // For numeric_limits
int main() {
int n = 0;
std::cin >> n;
if(std::cin.fail()) { // Check if cin had trouble
std::cout << "What you entered is not a number." << std::endl;
std::cin.clear(); // Clears error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Clears the rest of the input stream since cin stops at the first erroneous character
}
else
std::cout << "You entered " << n << std::endl;
return 0;
}