getting an infinite loop not making sense

When I enter a character or string I get a infinite loop. can some one help me please

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>
using namespace std;

int main ()
{
	
	int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	string month[] = {"January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    
	string answ, yes, no;
	int num;
	do {
		cout << "Enter a number between 1-12  ";
        cin >> num;
		
		if(num > 0 && num <= 12)
		{
			
		--num;
		cout << month[num] << " has " << days[num] << endl;
		cout << "would you like to continue?" << endl;
		cout << "yes or no" << endl;
		cin >> answ;
		}
                 // i think the problem is here in this else statement
		else
		{
			cout << "please enter a number between 1-12\n\n" << endl;
			continue;
		}
	} while ( answ != "no");

  
	

  system("pause");
  return 0;
}
Worked fine for me. What exactly are your indications of an infinite loop? What output are you seeing?
1
2
3
4
5
6
7
8
9
        cout << "Enter a number between 1-12  ";
        cin >> num;

        if (cin.fail())
        {
            cin.clear();
            cin.ignore(100,'\n');
            continue;
        }


If cin tries to read an int, but you give it a letter, the cin stream enters an error state. You then need to do two things:
• clear the error flags
• empty the input buffer (get rid of the wrong characters)
Last edited on
Topic archived. No new replies allowed.