INFINITE WHILE LOOP

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 do not post more than once:
http://www.cplusplus.com/forum/general/171187/
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

#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~";
exit(0);
}

return 0;
}



Try this.....
@LadyInRed7 Why to put exit in main()? You should use it only when there is no option to just return from main, as it doesn't unwound stack. And btw you mismatched curly brackets.
Last edited on
I keep getting infinite loops when ever my answer is out from Y or N.

Make sure the stream is still valid. If the user enters a non-number then you'll go into an infinite loop. Here's the code fixed up:
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
#include <iostream>
using namespace std;

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


    while(answer !='N' && cin){
	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~";
	}
    }
    return 0;
}

Looking at everyone's code help and solutions so far, are you supposed to implement a third case? For when the user selects 0, since 0 isn't negative, nor is it positive.
just add another else.
Technically, >=0 are all positive right? You could try incorporating it there itself..
0 is neither positive nor negative ;)
Topic archived. No new replies allowed.