Home Why do I keep getting an infinite loop?
Reply: 2

Why do I keep getting an infinite loop?

tidematic
1#
tidematic Published in 2018-01-11 21:37:46Z

I keep getting an infinite loop? What do i have to change to fix this? I am a beginner. Please help. I cant figure this out. I tried playing around with all the other loops but keep getting the same error.

#include <iostream> 

using namespace std;

int inputData();
int convertData();
int outputData();

int main ()
{
inputData();
return 0;
}

int inputData ()
{
int hours, minutes;
char am_pm;

cout << "Please enter hours: "; // ask user to input hours.
cin >> hours; 
do
{
if (hours > 23)
{
cout << "ERROR! Must be less than 23" << endl;
}
} 
while (hours > 23); // end of hours loop

cout << "Please enter minutes: ";
cin >> minutes;
do
{
if (minutes > 59)
{
cout << "Must be less than 59. Try again!" << endl;
}
}
while (minutes > 59);
}
Biagio Festa
2#
Biagio Festa Reply to 2018-01-11 21:41:47Z

Indentation can save your life.

---> do {
|     if (hours > 23) {
|       cout << "ERROR! Must be less than 23" << endl;
|      }
---  } while (hours > 23); // end of hours loop

For example, your first cycle (even the second) checks always the same condition but does not modify the state of your program, so how do you expect it will change the termination condition?

It should be something like (very minimal):

do {
  std::cin >> hours;
  if (hours > 23) {
    std::cout << "Error\n";
  }
} while (hours > 23);
Kamga Simo Junior
3#
Kamga Simo Junior Reply to 2018-01-11 21:50:12Z

You need to move your hour prompting statements ie. cout << "Please enter hours: "; // ask user to input hours. cin >> hours; to the do block of the loop.

do {
  cout << "Please enter hours: "; // ask user to input hours.
  cin >> hours;

  if (hours > 23)
  {
    cout << "ERROR! Must be less than 23" << endl;
  }
} while (hours > 23); // end of hours loop

So that if the user enters an invalid hour, he will be re-prompted until he enters a valid hour.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.307618 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO