C++ while in a if else

Started by
4 comments, last by graveyard filla 18 years, 10 months ago
hey i made this code:

#include <iostream>
using namespace std;

int main()
{
	int CountGames;

	cout << "How many games do you have: ";

	cin  >> CountGames;

	if(CountGames > 30 || CountGames == 30)
	{
		cout << "You got a lot games. you are a game freak\n\n\n";
	}
	else if(CountGames < 30 && CountGames > 0)
	{
		cout << CountGames << " Isn't much but atleast you got some\n\n\n";
	}

	else if(CountGames == 0)
	{
		cout << "You got no games. wtf you should get on.\n\n\n";
	}

	else if(CountGames < 0) 
	{ 
		while(CountGames <0)
		{

		cout << "you cannot have less then 0 games. duh\n";
		
		cout << "How many games do you have: ";

		cin  >> CountGames;
		}
	}

	system("pause");

	return 0;
}


but if you first enter -1 and then if you press the second time higher then 0 it pauses the program. how do i solve this?
Advertisement
try putting "cin.ignore();" in the while-loop before "cin >> CountGames;".
Also, why write "if(CountGames > 30 || CountGames == 30)"
if you can write "if(Countgame >= 30)"
#include <iostream>using namespace std;int main(){   int CountGames = -1;   do   {     cout << "How many games do you have: ";     cin  >> CountGames;        if(CountGames<0)        cout << "you cannot have less then 0 games. duh\n";   } while(CountGames<0);   if(CountGames > 30 || CountGames == 30)   {      cout << "You got a lot games. you are a game freak\n\n\n";   }   else if(CountGames < 30 && CountGames > 0)   {      cout << CountGames << " Isn't much but atleast you got some\n\n\n";   }   else if(CountGames == 0)   {      cout << "You got no games. wtf you should get on.\n\n\n";   }      system("pause");   return 0;}
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
If i was u i would validate your input as soon as it was entered e.g.

#include <iostream>
using namespace std;

int main()
{
int CountGames;

cout << "How many games do you have: ";

cin >> CountGames;
while(CountGames <0)
{

cout << "you cannot have less then 0 games. duh\n";

cout << "How many games do you have: ";

cin >> CountGames;
}

if(CountGames > 30 || CountGames == 30)
{
cout << "You got a lot games. you are a game freak\n\n\n";
}
else if(CountGames < 30 && CountGames > 0)
{
cout << CountGames << " Isn't much but atleast you got some\n\n\n";
}

else if(CountGames == 0)
{
cout << "You got no games. wtf you should get on.\n\n\n";
}

system("pause");

return 0;
}

thnx i forgot that the while loop should be above the else if loop
if(CountGames > 30 || CountGames == 30) should be if(CountGames >= 30) [grin]
FTA, my 2D futuristic action MMORPG

This topic is closed to new replies.

Advertisement