INFINITE WHILE LOOP

Aug 9, 2015 at 1:38pm
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')
}
Aug 9, 2015 at 2:43pm
Please do not post more than once:
http://www.cplusplus.com/forum/general/171187/
Aug 26, 2015 at 7:43am
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.....
Aug 26, 2015 at 10:50pm
@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 Aug 26, 2015 at 10:55pm
Sep 9, 2015 at 10:17pm
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;
}

Sep 18, 2015 at 12:07am
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.
Sep 18, 2015 at 12:41pm
just add another else.
Sep 23, 2015 at 7:04am
Technically, >=0 are all positive right? You could try incorporating it there itself..
Sep 23, 2015 at 9:13am
0 is neither positive nor negative ;)
Topic archived. No new replies allowed.