Fibonacci Sequence Program

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <sys/time.h>
#include <cstdlib>
#include <cmath>

using namespace std;

static int fib_iter(unsigned long n)
{
       if (n == 0) return 0;
       if (n == 1) return 1;

       unsigned long prevPrev = 0;
       unsigned long prev = 1;
       unsigned long 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.

Any help is appreciated.
You can use the isdigit function from <cctype>

http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

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;
}
Last edited on
Topic archived. No new replies allowed.