Sign in to follow this  
jordi_0071

C++ while in a if else

Recommended Posts

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?

Share this post


Link to post
Share on other sites
#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;
}

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this