VerTiGo_Etrex
VerTiGo_Etrex

Reputation: 149

Why does my program continuously loop?

I'm a cis221 student, and I've been assigned a piece of homework I simply cannot figure out...

The code below is the overloaded input operator for my "Fraction" class.

istream& operator>>(istream& in, Fraction& fract)
{
     cout << "Enter the whole number part for the fraction ";
     in >> fract.Whole;
     cout << "Enter the Numerator ";
     in >> fract.Numerator;
     cout << "Enter a Denominator ";
     in >> fract.Denominator;
     try
     {
         if (fract.Denominator == 0)
             throw(FractionException(fract, "Deno input was 0, setting to 1"));
     }
     catch(FractionException e)
     {
         fract.Denominator = 1;
         e.DisplayMessage();
     }
    fract.reduceFraction();
    return in;
}

Which is called in main.

void main()
{
    //Declarations
    srand((unsigned)time(NULL));
    int i = 0;
    Fraction fract[4];
    for (i=0; i<5; i++)
    {
        cin >> fract[i];
    }
    for (i=0; i<5; i++)
    {
        cout << fract[i];
    }
}

From what I understand, this code should execute perfectly; however, the code continuously loops. This is true even if the exception is never thrown.

I've put a watch on the loop control var "i" and literally watched it count from 0 to 4... I have NO idea what's wrong...

Thanks in advance!

Upvotes: 3

Views: 145

Answers (1)

Erik
Erik

Reputation: 91310

Fraction fract[4];
for (i=0; i<5; i++)

That's no good. Use Fraction fract[5] and you won't be overwriting random memory.

Upvotes: 4

Related Questions