Stop endless loop in terminal

Hello I am just learning loops in my c++ class.
I wrote a program that loops a random math problem generator...I know how to end the loop in the program. My problem, I goofed up in the program and now it's looping endlessly with out letting me give any input. How do you stop a an endless loop in the terminal window. Is there a way?

Im on a macbook pro.

If you want the code just let me know. But the code isn't my problem.
Last edited on
Input streams can enter a "bad" state. Usually this happens when you expect one kind of input and the user provides a different kind.

For example:

1
2
3
4
5
6
int foo = 0;
while(foo == 0)
{
  cout << "enter a nonzero number:  ";
  cin >> foo;
}


If the user inputs a character, like 'a', you get that endless loop. cin will enter a bad state and the 'a' will never be removed from the input buffer, so every time the cin >> foo line runs, it will see the same 'a'. It will never ask the user for more input.

What you need to do is check to make sure the stream is in a good state, and clear it/reset it if it's not.

1
2
3
4
5
6
7
8
9
10
11
12
int foo = 0;
while(foo == 0)
{
  cout << "enter a nonzero number:  ";
  cin >> foo;

  if(!cin.good())  // user gave bad input
  {
    cin.ignore(1000);  // dump the bad input
    cin.clear();  // reset cin to be in a good state
  }
}




But the code isn't my problem.


If the program isn't working the way you want, then the code is always the problem.

Don't ever assume your code is perfect or you'll never find bugs.
Last edited on
This might not at all be what you're after, but if you're simply looking for how to stop a program for executing in the terminal, it's ctrl-c on Unix.
Ahh yes, the code is always the problem. But I was just wondering how to stop the problem in my unix terminal. I have tried control + c, but for some reason it didn't work. That's why I'm a little baffled at the moment.

Also that cin.ignore and cin.clear might help with a different problem I am having.

Thanks for the help. Sorry for not being a little more clear in my question.
Maybe ctrl+z?
Topic archived. No new replies allowed.