1

I'm trying to make a program to calculate the factorial; I want from the user to enter only positive integers so I declared my variables as "unsigned int" and I used cin.fail() to prevent the user from entering letters or negative numbers. The problem is when I enter a "negative number" the cin.fail() doesn't work.

I tried to use istringstream and it didn't work too.

/*
A program used to get the factorial of a number
*/

#include <iostream>

using namespace std;

class Factorial
{
public:
    unsigned int CalcFactorial(unsigned int iEntry); //Function Prototype

private:
    unsigned int iResult = 0;
};

unsigned int Factorial::CalcFactorial(unsigned int iEntry)
{
    iResult = iEntry;
    for (unsigned int iCount = (iEntry - 1); iCount >= 1; --iCount)
    {
        iResult *= iCount;
    }

    return iResult;
}

int main()
{
    Factorial Fact;
    unsigned int num = 0;

    cout << "\t\t\t\t**********Welcome to Factorial Calculator**********\n\n\n";
    cout << "Please enter an Integer number ==> \n";
enterAgain:
    cin >> num;
    cout << "\n";

    if (cin.fail())
    {
        cout << "Please enter a correct number \n";
        cin.clear();
        cin.ignore(10000, '\n');
        goto enterAgain;
    }
    else
    {
        if (num == 0)
            cout << "Factorial of [" << num << "] is ==> " << 1 << "\n";
        else
        {
            if (num > 0 && num <= 12)
                cout << "Result is ==>" << Fact.CalcFactorial(num);
            else
            {
                cout << "The entered number is BIG, Try another number!\n";
                goto enterAgain;
            }
        }
    }
}
anastaciu
  • 23,467
  • 7
  • 28
  • 53
ahm
  • 11
  • 1
  • Does this answer your question? [Should reading negative into unsigned fail via std::cin (gcc, clang disagree)?](https://stackoverflow.com/questions/49921271/should-reading-negative-into-unsigned-fail-via-stdcin-gcc-clang-disagree) – walnut Feb 22 '20 at 17:13

0 Answers0