-3
int coefficient, exponent;
success = true // assume read is successful
cin >> coefficient >> exponent;
if (cin.eof())
{
   success = false;
}
while (!cin.eof() && success)
{
   if ((MIN_INDEX <= exponent) && (exponent <= MAX_SIZE - 1))
   {
       p[exponent] = coefficient;
   }
   else if ((exponent < MIN_INDEX) || (exponent > MAX_SIZE -1))
   {
       cout << "Error - invalid exponent (Must be between 0 and 20 inclusively)" << endl << "Please try again..." << endl << endl;
       success = false;
   }

   cin >> coefficient >> exponent;
}
return;

I have tried to the coefficient and exponent into an array. Whenever the user hits ctrl d, the read is terminated and array is successfully loaded. But somehow, after ctrl d, my program runs an infinite loop. Please help me to fix this. Thank you.

  • 3
    Does this answer your question? [Why is iostream::eof inside a loop condition (i.e. \`while (!stream.eof())\`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Revolver_Ocelot Sep 01 '22 at 21:47
  • 2
    In addition to the linked question, there is a chance that eof is never reached, because stream has failbit set and that makes every read fail and not actually try to read anything. – Revolver_Ocelot Sep 01 '22 at 21:49
  • Questions seeking debugging help should generally provide a [mre] of the problem, which includes a function `main` and all `#include` directives, as well as the exact input required to reproduce the issue. Without this information, we can only speculate on possible reasons for the error. – Andreas Wenzel Sep 01 '22 at 21:59
  • 1
    Revolver_Ocelot's probably right, but without the [mre] we can't be certain. – user4581301 Sep 01 '22 at 22:32

1 Answers1

1

cin.eof() is not the way to check for successful reads. Try this instead:

int coefficient, exponent;
while (cin >> coefficient >> exponent)
{
   if ((MIN_INDEX <= exponent) && (exponent <= MAX_SIZE - 1))
   {
       p[exponent] = coefficient;
   }
   else
   {
       cout << "Error - invalid exponent (Must be between " << MIN_INDEX << " and " << MAX_SIZE - 1 << " inclusively)" << endl << "Please try again..." << endl << endl;
   }
}
return;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770