I am creating a simple code to take integer value 10 times. If at any point, the users enters the value '5', the system should print a message, "You entered 5, you lose". Here is the code
int main()
{
int num = 0;
int i;
for (i = 1; i<= 10; i++)
{
cout << "Enter a number other than 5\n";
cin >> num;
if (num == 5)
{
cout << "Hey, you entered 5. You lose!\n";
break;
}
}
cout << "You win!";
return 0;
}
Now what I dont know is, how do close the program after users enters 5. I am very new to coding so Im really sorry if this question sound stupid. Also, it would be vet nice of you if you could explain in the most easiest way you can. Thank you
You could do this:
for (i = 1; i<= 10; i++)
{
cout << "Enter a number other than 5\n";
cin >> num;
if (num == 5)
{
cout << "Hey, you entered 5. You lose!\n";
return 0; // This will end function main and return 0. Thus your program will end.
}
}
And some more reading.
The way you had it break would simply stop the for loop. This however:
cout << "You win!";
would still get printed. If you use return, no more statements from main will get executed. Because return will end the function in which it is called, in this case, main.
Now what I dont know is, how do close the program after users enters 5.
Replace
break;
with
exit(0);
or
return 0;
break will only exit from the loop, and you're printing cout << "You win!"; unconditionally.
The other two approaches mentioned above are undoubtedly the best. But still, if you have some unfinished business that you want to take care of even after the user enters 5 you can take help of a temporary variable say temp.
int main()
{
int num = 0,tmp=0;
int i;
for (i = 1; i<= 10; i++) {
cout << "Enter a number other than 5\n";
cin >> num;
if (num == 5) {
tmp=1;
cout << "Hey, you entered 5. You lose!\n";
break;
}
//unfinished work
}
//unfinished work
if(tmp==0)
cout << "You win!";
return 0;
}
Related
Write a program that continues to ask the user to enter any number other than 5 until the user enters the number 5.
Then tell the user "Hey! you weren't supposed to enter 5!" and exit the program.
★ Modify the program so that after 10 iterations if the user still hasn't entered 5 will tell the user "Wow, you're more patient then I am, you win." and exit.
★★ Modify the program so that it asks the user to enter any number other than the number equal to the number of times they've been asked to enter a number. (i.e on the first iteration "Please enter any number other than 0" and on the second iteration "Please enter any number other than 1"m etc. etc. The program must behave accordingly exiting when the user enters the number they were asked not to.)
I got most of the program to work. I have it to a point where it asks for a number starting at 0 and going up, it gives the user the patient message after 10 tries, and exits the program if they enter the number they are not supposed to. However if the user inputs the number above what it tells you not to enter, the program exits with no message.
I do not really know what to search to fix this issue. I have however tried to move some things around, and got rid of some redundant variables.
Any hints would be appreciated, please do not give me the answer up front! Here's what I have so far.
#include <iostream>
int main()
{
const int GUESS = 1; // constant for number of tries
const int PATIENCE = 10; // constant for message at 10 tries
int UserNum; // player input
int InputNum = GUESS; // intializes GuessNumber
// asks for player input
do
{
std::cout << "Enter any number other then "<< InputNum << ": ";
std::cin >> UserNum;
// exits program if user inputs the number displayed
if (UserNum == InputNum)
{
std::cout << "Hey! you weren't supposed to enter " << InputNum << "!\n";
}
// increase the Guess counter if they dont enter the number displayed
else if (UserNum != InputNum)
{
InputNum++;
}
if (InputNum == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.\n";
break;
}
} while (UserNum != InputNum);
return 0;
}
your problem is in do while loop condition
statements are executed first and condition are checked later
for example
InputNum is initialized as 1
so if you enter 2 as input for UserNum , in the else if condition ,InputNum will be incremented to 2
when this condition is evaluated
while (UserNum != InputNum)
it will be false as 2==2
loop breaks
solution
change PATIENCE = 11 and use
while (1)
// this will run infinitely but it will break after 10 iteration or when u press the same number which u shouldn't
instead of
while (UserNum != InputNum)
the full program
#include <iostream>
int main()
{
const int GUESS = 1; // constant for number of tries
const int PATIENCE = 11; // constant for message at 10 tries
int UserNum; // player input
int InputNum = GUESS; // intializes GuessNumber
// asks for player input
do
{
std::cout << "Enter any number other then " << InputNum << ": ";
std::cin >> UserNum;
// exits program if user inputs the number displayed
if (UserNum == InputNum)
{
std::cout << "Hey! you weren't supposed to enter " << InputNum << "!\n";
break;
}
// increase the Guess counter if they dont enter the number displayed
else if (UserNum != InputNum)
{
InputNum++;
}
if (InputNum == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.\n";
break;
}
} while (1);
system("pause");
return 0;
}
Hey try this program it does exactly what you want.
#include <iostream>
int main ()
{
int GUESS = -1; //loop variable
const int PATIENCE = 10; // constant for message at 10 tries
int InputNum; // input from user
std::cout << "PATIENCE Test" << "!\n";
do
{
GUESS++;
// asks for player's input
std::cout << "Enter any number other than " << GUESS << ": ";
std::cin >> InputNum;
// exits program if user inputs the number displayed
if (GUESS == InputNum)
{
std::
cout << "Hey! you weren't supposed to enter " << GUESS << "!\n";
break;
}
if (GUESS == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.\n";
break;
}
}
while (GUESS != InputNum);
return 0;
}
I am implementing a Guessing game where computer generates random number with the following code:
int main()
{
srand(time(NULL));
while (true){
int num = rand() % 10, guess, tries = 0;
while (true){
cout << "Enter number 1 to 10:";
cin >> guess;
if (tries > 2)
{
break;
}
if (guess > num)
{
cout << "Too High ! Try again"<<endl;
}
if (guess > 10)
{
cout << "Error ReEnter 1 to 10\n";
}
else if (guess < num)
{
cout << "Too Low! Try again"<<endl;
}
else
{
break;
}
tries++;
}
if (tries > 2)
{
cout <<"\nYou ran out of tries!\n";
cout << "\nThe answer is:" << num << endl;
}
else
{
cout << "\nCONGRATZ!! You guess correctly!\n";
}
return 0;
}
}
One of the problems is: yet when user attempt 3 times, the program shows "ran out of tries" even though the user input is correct on 3rd try.
Questions:
1.How do I inform user that their input exceeds 10 and show an error message to user to enter values from 1 to 10 ?
2.How to correct the aforementioned problem?
instead of writing the program for you here is some pseudo code.
get a random number rand()%10+1 1..10 call it R
loop
get user input N
if N == R then show OK and break loop
if N < R show too low
else show too high
increment tries
if tries == 3 then break loop
end loop
You have too many if else conditions that make your code unnecessarily complex, to answer your second question specifically the unwanted behaviour is caused from the:
if (tries > 2)
{
break;
}
which exits the loop regardless of the guess, as it is dependant only on the number of tries. Regarding your first question, I decided to provide you with more simple implementation that includes an answer to it as well.
You could replace your while loop with a do-while loop, terminated when the random number is guessed, i.e.:
int main(){
// initialize random seed
srand (time(NULL));
// generate a random number within [1,10]
int secretRandom = rand() % 10 + 1;
// initialize
int yourGuess = 11;
// input loop
string promptMessage = "Type a a number from 1 to 10."
do{
cout << promptMessage << '\n';
// read input
cin >> yourGuess >> endl;
// guessed number relatively to the randomly generated
if (secretRandom < yourGuess) cout << "The secret number is lower\n";
else if (secretRandom > yourGuess) cout << "The secret number is higher\n";
}while(yourGuess != secretRandom)
// if you guess the random number exit the loop and display success message
cout << "You guessed right!\n";
return 0;
}
To reduce the amount of guesses to specific number you can enclose the do-while loop and the success message in a for loop, for example:
int numberOfGuesses = 3;
for (int i = 0; i <= numberOfGuesses; ++i){
//...
}
If you want to enforce the user to input a number in the range from 1 to 10, you could do it by:
int yourGuess = 11;
int lowerBound = 0;
int upperBound = 10;
do{
cin >> yourGuess;
// not type safe
}while(yourGuess < lowerBound || yourGuess > upperBound);
I am just a newbie to programming and I was trying to write a while loop that runs as long as the input (num) is not a integer which doesn't ends with zero. What happen is when I enter a number that ends with zero, the program runs the loop correctly, but when i enter something nonsense such as rofl the program only print The input is not valid. and won't repeat the loop. I have tried to look for solutions but I am still stuck after a hour. Anyone can help me here? Thx so much!
void rev_sum() {
int num;
int a = 1;
while (a < 2) {
cout << "Please input a natural number without zero at the end:\n";
cin >> num;
if (!cin) {
cout << "The input is not valid.\n";
cin.clear();
cin.ignore(INT_MAX);
}
if (num % 10 == 0) {
cout << "The number cannot have zero at the end\n";
} else {
cout << "gj\n";
break;
}
}
}
Try replacing
cin.ignore(INT_MAX);
With
cin.ignore(numeric_limits<streamsize>::max(), '\n');
And change the
if (num % 10 == 0)
To
else if (num % 10 == 0)
Your final code should look like this:
void rev_sum() {
int num;
int a = 1;
while (a < 2) {
cout << "Please input a natural number without zero at the end:\n";
cin >> num;
if (!cin) {
cout << "The input is not valid.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else if (num % 10 == 0) {
cout << "The number cannot have zero at the end\n";
} else {
cout << "gj\n";
break;
}
}
}
if (num % 10 == 0) {
could be
else if (num % 10 == 0) {
otherwise the other else case might get executed
You set a = 1 at the start of the loop and then never change a which means the only way to leave your while loop is if you hit the break statement. If your loop is not looping then it must be stuck somewhere. I'm unfamiliar with the statements if (!cin) and cin.ignore(...) so those are top suspects to check (or change). The statement cin >> num; completes no matter what they type so you can check to see what 'num' is equal to when you enter "rofl". Then after it fails, you still use num so you are processing this unintentional entry. You can add continue; after cin.ignore(...) to jump back to the top of the while loop and ask the question again. You can also print something after the while loop in order to know when you get out.
With all that said, I would never trust the user to enter acceptable information and I would never trust cin to process it for me. Personally, I would read cin as a string using cin.getline(buffer, buffer_size); And then I would complain to the user if they filled the buffer or gave me something that was not an integer (which you can check with a function like scanf()). Then you can spit back exactly what they gave you and you can be specific about your complaint.
Would it not make more sense to only check that the number ends in 0 if the input was valid....
void rev_sum() {
int num;
int a = 1;
while (a < 2) {
cout << "Please input a natural number without zero at the end:\n";
cin >> num;
if (!cin) {
cout << "The input is not valid.\n";
cin.clear();
cin.ignore(INT_MAX);
} else {
if (num % 10 == 0) {
cout << "The number cannot have zero at the end\n";
} else {
cout << "gj\n";
break;
}
}
}
}
cin.ignore(numeric_limits<streamsize>::max())
I've been trying to make a simple game where the computer generates a random number and you try to guess it. It also stores the amount of guesses you make "tries".
However, when I run the program, it simply prints: "Let's play a game. I'll think of a number 1-100. Try to guess it."
Here's my code:
#include <iostream>
int main()
{
using namespace std;
int the_number;
int guess;
int tries;
the_number = rand() % 101 + 1;
cout << "Let's play a game!";
cout << "I will think of a number 1-100. Try to guess it.";
cout << endl;
cin >> guess;
for (tries = 0; tries++;)
{
if (guess == the_number)
{
cout << "You guessed it!";
cout << "And it only took you: " << tries;
}
else if (guess < the_number)
{
cout << "Higher";
tries++;
}
else if (guess > the_number)
{
cout << "Lower";
tries++;
}
else
cout << "That's not even in range!";
return 0;
}
}
I don't understand why this doesn't work, could someone explain why not?
The reason your program does not print anything after "Let's play a game. I'll think of a number 1-100. Try to guess it." is the way you have written your for loop.
for ( tries = 0; tries++; )
breaks out of the loop without doing anything because tries++ evaluates to 0.
Also, for your program to work correctly, you need to add more code to read guesses. Something like the code below, should work.
for (tries = 0; ; tries++)
{
if (guess == the_number)
{
cout << "You guessed it!";
cout << "And it only took you " << tries << " tries.\n";
break;
}
else if (guess < the_number)
{
cout << "Higher";
cin >> guess;
}
else if (guess > the_number)
{
cout << "Lower";
cin >> guess;
}
}
You can define a couple of variables that will make your code more understandable, something like this :
#include <iostream>
using namespace std;
int main()
{char EndGame = 'N';
int MyNumber = 150 , playerguess;
cout << "I have a number between 1 and 100.\nCan you guess my number ??\nPlease type your first guess.\n?" << endl;
do{
cin >> playerguess;
if (playerguess > MyNumber) {
cout << " Too High. Try again." << endl;
}
else if (playerguess == MyNumber) {
cout << "Excellent ! You Got It ! \n If you want to exit press Y" << endl;
cin >> EndGame;
break;
}
else {
cout << " Too Low. Try again." << endl;
}
} while (1);
return 0;
}
This will make the number equal to 150. Each time the user inputs a value, the console will determine whether it is higher, lower or equal to the number.
If you want instead to make it a random number each time, you can simply use the <random> library and use the module operator with a number like 100 or 101. Then, you can add 1; this will generate only positive integers.
You should use while loop here, not for:
while (the_number != guess)
{
//
//
}
And try using the new <random> header instead of rand() function:
#include <random>
std::random_device rd;
std::default_random_engine engine(rd());
std::uniform_int_distribution<int> uniform_dist(1, 100);
the_number = uniform_dist(engine);
Your for loop is wrong (it needs 3 things: initialization, check condition and the todo step after each loop.
For example:
for (tries = 0; tries < 5; tries++)
Also you loop the guessing part, but you forget to ask the user for a new number. I would suggest to move the cin << guess into the for loop.
void offer_help();
bool play_one_game();
int main() {
offer_help();
play_one_game();
}
void offer_help() {
int help_response;
cout << "Need help? (0/1) ";
cin >> help_response;
if (help_response == 1)
cout << "I will generate a pattern of 4 numbers, each in the range 0 through 9.\n Each guess that you enter will be a line containing 4 integers,\n separated by spaces, such as:\n\t 2 4 7 1\n FOr each guess, I will echo back a lost consisting of\n 0's and 1's, with a 1 in a given position meaning that\n you guessed the number, and a zero meaning that you didn't.\n For example, if the actual solution was 2 3 6 1, I'll respond\n\t 1 0 0 1\n See how many guesses it takes you to get the solution!\n\n If you want to give up, type a negative number for one of\n your guesses, and we'll tell you what the pattern was.\n\n";
}
bool play_one_game() {
srand(time(0)); //needed to start randint
vector<int> solution; //vector of 4 randomly generated
//solutions
vector<int> guess; //vector containing user guesses.
vector<int> result;
int guess_input;
for(int i = 0; i < solution.size(); ++i)
solution[i] = randint(10);
int trial_number = 0; //int that shows what guess the user is on
while (play_one_game() == true) {
//ask user for inputs.
cout << "Guess #" << ++trial_number << "? ";
for (int i = 0; i < guess.size(); ++i){
cin >> guess_input;
guess.push_back(guess_input);
}
//outputs error if user inputs a letter.
if (!cin) {
cerr << "Bad input data! Feed me numbers!\n";
return 43;
}
if (cin < 0){
cout << "Too bad! Solution was " << endl;
for(int i = 0; i < result.size(); i++)
cout << (result[i]);
}
//determines if user correctly guessed any of the
//numbers and tells the user which is correct.
for (int i = 0; i < result.size(); i++) {
if (guess[i]==solution[i])
cout << 1 << " ";
else if (guess[i]!=solution[i])
cout << 0 << " ";
}
cout << endl;
// playagain();
cout << endl << "Play again (0/1)? ";
int replay;
cin >> replay;
if (replay == 0) {
play_one_game() == false;
return 5;
}
else if (replay == 1)
play_one_game() == true;
else {
cerr << "wat?\n";
return 10;
}
}
}
This is designed to allow a player to guess a pattern of random numbers.
No idea why I am getting a segmentation fault. The program is supposed to call the offer_help function, then the play_one_game function within main function. Then it should ask the player whether he wants to play again. If no, then bool play_one_game should be set to false and it should exit.
This is related to the play_one_game bool function.
You're getting a segmentation fault, because you end up in an endless recursion in the following line:
while (play_one_game() == true) {
play_one_game will call play_one_game in this line, and this will call play_one_game in the same line again. This will result in a stack overflow at last.
Better use some bool keepPlaying; and while(keepPlaying) instead.
EDIT: Well, this is a little bit more than a simple answer, but I like games, so... have a look at the following code:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
bool play_one_game();
void offer_help() {
int help_response;
std::cout << "Need help? (0/1) ";
std::cin >> help_response;
if (help_response == 1)
std::cout << "I will generate a pattern of 4 numbers, each in the range 0 through 9.\n"
"Each guess that you enter will be a line containing 4 integers,\n"
"separated by spaces, such as:\n"
"\t 2 4 7 1\n"
"For each guess, I will echo back a lost consisting of\n"
"0's and 1's, with a 1 in a given position meaning that\n"
"you guessed the number, and a zero meaning that you didn't.\n"
"For example, if the actual solution was 2 3 6 1, I'll respond\n"
"\t 1 0 0 1\n"
"See how many guesses it takes you to get the solution!\n\n"
"If you want to give up, type a negative number for one of\n"
"your guesses, and we'll tell you what the pattern was.\n\n";
}
int main() {
offer_help();
srand(time(0)); // Initialize random numbers with current time as seed
while(play_one_game()); // if play_one_game returns true, play again
}
bool play_one_game() {
std::vector<int> solution(4); // Four solutions for our guessing game
std::vector<int> guess; // User guesses
for(unsigned i = 0; i < solution.size(); ++i)
solution[i] = rand() % 10;
int trial_number = 0; //int that shows what guess the user is on
bool keepPlaying = true;
while(keepPlaying){
std::cout << "Guess #" << ++trial_number << "? ";
guess.clear(); // Clear old guesses
for(unsigned i = 0; i < solution.size(); ++i){
int guess_input;
//outputs error if user inputs a letter.
if (!(std::cin >> guess_input)) {
std::cerr << "Bad input data! Feed me numbers!\n";
std::cerr << "Try again!" << std::endl;
std::cin.clear(); // Clear flags
continue;
}
if (guess_input < 0){
std::cout << "Too bad! Solution was " << std::endl;
for(unsigned i = 0; i < solution.size(); i++)
std::cout << (solution[i]);
keepPlaying = false;
break;
}else
guess.push_back(guess_input);
}
if(!keepPlaying)
break;
if(solution.size() != guess.size()){
std::cerr << "Wrong number of guesses, try again!" << std::endl;
continue;
}
//determines if user correctly guessed any of the
//numbers and tells the user which is correct.
bool correct = true;
for (unsigned i = 0; i < solution.size(); i++) {
if (guess[i] == solution[i])
std::cout << 1 << " ";
else{
correct = false;
std::cout << 0 << " ";
}
}
if(correct){
std::cout << "Congratulations - you won!" << std::endl;
break;
}
std::cout << std::endl;
}
int replay = -1;
do{
// Ask user for input until input is 0 or 1
std::cout << std::endl << "Play again (0/1)? ";
std::cin >> replay;
}
while(replay != 0 && replay != 1);
return static_cast<bool>(replay); // return user replay answer (false/true)
}
Try to keep your code as simple as possible. Welcome to SO. And don't expect future answers to be that excessive.
You're never inserting anything into your solution vector. You just declare the vector, and then say:
for(int i = 0; i < solution.size(); ++i)
solution[i] = randint(10);
...which won't do anything since at this point solution.size() == 0. Later, when you iterate over your result vector, you end up accessing invalid elements in your empty solution vector. You also can't assume that the result vector and solution vector are the same size.