WHILE and INFINITE LOOPS

Hello guys! I need your help. I keep getting infinite loops when ever my answer is out from Y or N.

#include <iostream>
using namespace std;

int main(){
int number;
char answer= 'Y';


while(answer !='N'){
cout << "Type a number: ";
cin >> number;

if(number <0){
cout << number << " is a negative number." << endl;
}

else
if(number >0){
cout << number << " is a positve number." << endl ;

}

cout << "Repeat? [Y/N]: ";
cin >> answer;
answer = toupper(answer);

if(answer == 'n' || answer == 'N'){
cout << "Good bye~";
}

else
if(answer !='N')
}
Please edit your post and make sure your code is [code]between code tags[/code] so that it has line numbers and syntax highlighting, as well as proper indentation.

This code does not compile.
To fix the infinite loop you could put the cin >> answer; statement in a do..while loop which will loop while answer is different from Y, y, N and n.

I edited your code a little bit and I think this is what you were trying to do.

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
#include <iostream>
using namespace std;

int main()
{
	int number;
	char answer = 'Y';

	while(answer != 'N' && answer != 'n')
	{
		cout << "Type a number: ";
		cin >> number;

		if(number < 0)
		{
			cout << number << " is a negative number." << endl;
		}
		else if(number > 0)
		{
			cout << number << " is a positve number." << endl ;
		}

		do
		{
			cout << "Repeat? [Y/N]: ";
			cin >> answer;
		} while (answer != 'Y' && answer != 'y' && answer != 'N' && answer != 'n');
		
		
		if(answer == 'n' || answer == 'N')
		{
			cout << "Good bye~";
		}				
	}
	return 0;
}


Also, please surround your code with "code" tags, so we can read it better.
Last edited on
Topic archived. No new replies allowed.