Reputation: 389
I started trying to learn C++ tonight and I'm just messing around in an IDE right now. How can I make this simple program not close the program until you guess the correct number (5, 6, or 7)?
As it stands it will take one input, then say press any key to close, instead of allowing me to keep guessing.
#include <iostream>
int main()
{
int favorite_number;
std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;
if(favorite_number == 5 || favorite_number == 6 || favorite_number == 7)
{
std::cout << "Amazing!! That's my favorite number too!";
}
std::cout << "Nice try, but that's not my favorite number" << std::endl;
return 0;
}
Upvotes: 0
Views: 630
Reputation: 464
I am glad you found a solution! Furthermore, take a look over this code:
int main()
{
int favorite_number;
while(1)
{
std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;
if(5 == favorite_number || 6 == favorite_number || 7 == favorite_number)
{
std::cout << "Amazing!! That's my favorite number too!";
return 0;
}
else
std::cout << "Nice try, but that's not my favorite number" << std::endl;
}
}
You can make the loop infinite without using that bool completed. This way it will run as long as the number inserted is different from one of the favorite numbers. Also, the last return in your code is extra. Changing the order inside if(5 == favorite_number)
, for example, is considered a good practice because you might write by mistake favorite_number = 5
(assignment), which is valid and this way you will have a bug harder to find.
Upvotes: 1
Reputation: 389
Thanks got it figured out!
#include <iostream>
int main()
{
int favorite_number;
bool completed = false;
while(completed == false)
{
std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;
if(favorite_number == 5 || favorite_number == 6 || favorite_number == 7)
{
std::cout << "Amazing!! That's my favorite number too!";
completed = true;
return 0;
}
else
std::cout << "Nice try, but that's not my favorite number" << std::endl;
}
return 0;
}
Upvotes: 3