Ending a loop once the user is wrong twice? - c++

I am doing a quiz and testing the user. If the user is wrong he is allowed a second chance or skip, if he chooses 2nd chance and is wrong again, the game is over. How do I break out of this loop to end the game? I tried a do while loop,
do { stuff} while (wrong<2) while counting ++wrong;
every time he's wrong, but didnt work.
I have labeled the ++wrong with // statements below
void player_try (string questions[][5], char answers[])
{
char user_guess;
int m = 0;
srand(time(NULL));
int x;
int choice;
int wrong =0;
for (m=0; m<7; m++)
{
do
{
x = (rand() % 7);
cout << user_name << ": Here is question number " << m+1 << endl;
cout << m+1 << ". " << questions[x][0]<< endl;
cout << "A. " << questions[x][1]<< endl;
cout << "B. " << questions[x][2]<< endl;
cout << "C. " << questions[x][3]<< endl;
cout << "D. " << questions[x][4]<< endl;
cin >> user_guess;
user_guess = toupper(user_guess);
while (!(user_guess >= 'A' && user_guess <= 'D'))
{
cout << "Please choose a valid answer.";
cin>> user_guess;
}
if (user_guess != answers[x])
{
cout <<"Wrong!" <<endl;
++wrong; // THIS IS WHERE I COUNT WRONG ONCE
cout << "Skip this question or take a chance at greatness?" << endl;
cout << "Press 1 to skip, press 2 to take a chance at greatness" << endl;
cin >> choice;
if (choice == '1')
{
cout << "we shall skip this question." << endl;
}
else
{
cout << "I applaud your bravery." << endl;
cout << user_name << ": Here is question number " << m+1 << endl;
cout << m+1 << ". " << questions[x][0]<< endl;
cout << "A. " << questions[x][1]<< endl;
cout << "B. " << questions[x][2]<< endl;
cout << "C. " << questions[x][3]<< endl;
cout << "D. " << questions[x][4]<< endl;
cin >> user_guess;
user_guess = toupper(user_guess);
while (!(user_guess >= 'A' && user_guess <= 'D'))
{
cout << "Please choose a valid answer.";
cin>> user_guess;
}
}
if (toupper(user_guess) != answers[x])
{
cout <<"Wrong!" <<endl;
++wrong;; // THIS IS WHERE I CANT WRONG TWICE
}
else
{
cout << "correct!" << endl;
}
}
else
{
cout << "correct!" << endl;
}
}
while(wrong < 2);
}
}

Change your function return type to an integer. That simply means changing "void" to "int."
Then, inside the function place a return 0; at the point you want your function to terminate. Be sure you include another return 1; for the case that the user wins too.
This is how the main() function works. Consider:
int main()
{
string tester = "some string";
if(tester == "some string")
return 1;
cout << "Hey!"
return 0;
}
In the above case, main() terminates at the "return 1;" because the if statement was TRUE. Note that "Hey!" is never printed. It'll work the same way for your function.
As a plus, you can use that return value to let OTHER functions (such as main()) know if the function terminated because the user won (it returned 1), or lost (it returned 0).
Yes, a break statement is also a valid way to terminate the loop, but I submit that this method is the safer, cleaner way to go about it. In general, we like to know whether a function or program was successful or not.

You can use a break; statement if the person has gotten the answer wrong twice.
As per comments. You can shed the do while loop in favour of one for loop. Just put a break at the bottom if the wrong guesses are 2

There are several great suggestions for refactoring the code to remove the duplication of effort here, but to get the program functioning immediately, you've got to break out of the for loop surrounding the do { } while(wrong < 2) loop.
A simple way to do this is to modify the for loop to test the wrong variable also. The added benefit is, if I'm reading everything correctly, you'll no longer need the do{ } while(); loop.
for (m=0; m<7 && wrong < 2; m++)

Related

How create a guessing game with letters. For example I need to guess a letter from the word fallout. Which functions are useful

I am creating a guessing game. I need to ask the user to input a letter from a word like fallout. The have that letter they had inputted be correct or incorrect. I am using functions like srand(time(NULL)), rand(), psw.length. once the user inputs a letter and if they are wrong a life is deducted live--.
If they get it right they can move on to the next question with a full 5 lives. I don't know what functions I am missing if I need an array etc.
I have tried applying the rand() && psw.length together in order to at least try to randomize the letter choice so that the user might have a chance to guess the random letter from the word "fallout" but to no avail.
I have made some progress I started with the numerical portion of the code instead of focusing on the whole thing at once. Then now I have to start on the alphabetical portion of the code itself I am organizing my thoughts to simpler terms.
Now onto the alphabetical functions of the code....I now need to randomize letters for the user to answer with the correct letter of the word using functions.
I am trying to make the second answer2 = rand() % word2.length function work could anyone help me here it automatically runs the code giving a positive score to the user....
include <iostream>
#include <string>
#include <time.h>
#include <cstdlib>
using namespace std;
int lives = 3;
int guess;
int guess2;
int answer = 0;
int answer2 = 0;
int i;
int score = 0;
char letter, letter2;
string word = "fallout";
string word2 = "psw";
int main()
{
srand(time(NULL));
cout << "Welcome to the guessing game!" << endl;
cout << "*****************************" << endl;
system("PAUSE");
system("cls");
answer = rand() % 2 + 1;
lives = 3;
do {
cout << "What is a number between 1 and 2? Can you guess it in\n" << endl << lives << endl << "tries?" << endl;
cin >> guess;
if (guess == answer)
{
cout << "You won!!" << endl;
score++;
}
else if (lives == 0)
{
cout << "Your score" << endl << score;
system("PAUSE");
return 0;
}
else
{
cout << "Incorrect try again!" << endl;
lives--;
system("PAUSE");
system("cls");
}
} while (guess != answer);
cout << "You won your score is" << score << endl;
system("PAUSE");
system("cls");
answer = rand() % 3 + 1;
lives = 3;
do {
cout << "What is a number between 1 and 3? Can you guess it in" << endl << lives << "tries?" << endl;
cin >> guess;
if (guess == answer)
{
cout << "You won!!" << endl;
score++;
}
else if (lives == 0)
{
cout << "Your score" << endl << score;
system("PAUSE");
return 0;
}
else
{
cout << "Incorrect try again!" << endl;
lives--;
system("Pause");
system("cls");
}
} while (guess != answer);
cout << "You won your score is" << score << endl;
system("PAUSE");
system("cls");
answer = rand() % 5 + 1;
lives = 3;
do {
cout << "What is a number between 1 and 5? Can you guess it in\n" << endl << lives << "tries?" << endl;
cin >> guess;
if (guess == answer)
{
cout << "You won!!" << endl;
score++;
}
else if (lives == 0)
{
cout << "Your score" << endl << score;
system("PAUSE");
return 0;
}
else
{
cout << "Incorrect try again!" << endl;
lives--;
system("cls");
}
} while (guess != answer);
cout << "You won your score is " << score << endl;
system("PAUSE");
system("cls");
answer = rand() % word.length();
lives = 3;
do
{
cout << "Select the correct letter in the word '" << word << "': ";
cin >> guess;
if (guess == letter)
{
cout << "You Won!" << endl;
score++;
}
else if (lives == 0)
{
cout << "The correct answer is:" << endl;
cout << word[answer];
}
else
{
cout << "Incorrect Try Again" <<
lives--;
}
} while (guess != letter);
cout << "You won your score is " << score << endl;
system("PAUSE");
system("cls");
How can I make this code run well can anybody help me I just need advice on this function here... It keep giving the user a score++ automatically. Is their a simple fix for this. I am a rookie so if there is a basic trick here it would help!
answer2 = rand() % word2.length();
lives = 3;
do
{
cout << "Select the correct letter in the word '" << word2 << "': ";
cin >> guess2;
if (guess2 == letter2)
{
cout << "You Won!" << endl;
score++;
}
else if (lives == 0)
{
cout << "The correct answer is:" << endl;
cout << word2[answer2];
}
else
{
cout << "Incorrect Try Again" <<
lives--;
}
} while (guess2 != letter2);
cout << "You won your score is " << score << endl;
system("PAUSE");
system("CLS");
}
First of all, in C++ you have some different ways to randomize a value. rand() highly not recommended.
From cppreference:
There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls). rand() is not recommended for serious random-number generation needs, like cryptography.
Instead, you can use:
#include <random>
int main() {
/*...*/
// Seed with a real random value, if available
std::random_device r;
// Choose a random mean between 1 and 6
std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(1, 7);
answer = uniform_dist(e1);
/*...*/
return 0;
}
Read more about random: https://en.cppreference.com/w/cpp/numeric/random
For loop - Condition problem: for (int i = 0; i < guess; i++) - The condition here seems wrong. Why does this loop runs until i is bigger then the user guess? I think a better way for your target is to use while loop, until the user have no lives:
int lives = 5;
size_t guess_number = 1;
/*...*/
while (lives) {
cout << "Guess" << guess_number++ << endl;
/*...*/
}
Stop the loop: Whenever the user successfully guess the letter (or the letter's place in the word), you might considering random a new letter, a new word, or just stop the game and exit the loop (with break).
The word FALLOUT: Currently, in your code, the word fallout ia a variable name, and not a variable content. start with replacing this name to something like word_to_guess, and put the value fallout into it.
string fallout;
to:
string word_to_guess = "fallout";
Now that you have done it, you can make you code more generic to another words, by choosing a random number between 1 to word_to_guess.size():
std::uniform_int_distribution<int> uniform_dist(1, word_to_guess.size());
Now you want to convert user's guess and computer's guess to letters:
/**
* guess >= 1 - The user have to guess a letter from the beginning of the word (and not before it).
* guess <= word_to_guess.size() - The user can't guess a letter that not exists in the word.
* word_to_guess[guess - 1] == word_to_guess[answer - 1] - Compare the user's letter to the computer's letter
*
* word_to_guess[answer - 1] - You might consider to replace this with word_to_guess[answer], and just random
* a number from 0 to word_to_guess.size() - 1
*/
if (guess >= 1 && guess <= word_to_guess.size() && word_to_guess[guess - 1] == word_to_guess[answer - 1]) {
cout << "You Won" << endl;
break; // Or random new letter/word etc...
}

Add a countdown timer to a math program quiz

I am trying to add a countdown timer to this program. I would like the timer to start when the first math fact question is asked and upon expiration i want the program to give the grade. What's the code to do this in c++ if possible?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
int main(int args, char* argv[])
{
int i;
int result;
int solution;
char fact;
bool done = false;
int correct = 0;
int count = 0;
do {
try {
cout << "Enter (m)ultiplication or "
<< "(a)ddition." << endl; /*or (s)ubstraction. */
cin >> fact;
while (!cin)
throw fact;
if (fact != 'A')
if (fact != 'a')
if (fact != 'M')
if (fact != 'm')
while (!cin)
throw fact;
cout << "Now, enter the number of the fact that
you would like to do." << endl;
cin >> i;
int wrong = 0;
int score = 0;
int j = 0;
while (!cin)
throw i;
switch (fact) {
case 'm':
case 'M':
while (j < 13) {
cout << "What's " << i << " x " << j << "?" << endl;
cin >> result;
while (!cin)
throw result;
solution = i * j;
if (result == solution) {
cout << "Great Job! That is the correct answer for the problem "
<< i << " x " << j << "." << endl;
cout << endl;
cout << endl;
cout << endl;
score++;
j++;
cout << endl;
}
if (result != solution) {
cout << "Oh no! " << result << " is NOT the correct answer for "
<< i << " x " << j << "." << endl;
wrong = wrong + 1;
count++;
}
if (count == 3) {
cout << "The correct answer is " << i * j << "." << endl;
j++;
wrong = wrong - 3;
count = 0;
}
if (count == 1) {
cout << endl;
count--;
wrong = wrong - 1;
}
if (count == 2) {
cout << endl;
count--;
wrong = wrong - 2;
}
}
case 'a':
case 'A':
while (j < 13) {
cout << "What's " << i << " + " << j << "?" << endl;
cin >> result;
while (!cin)
throw result;
solution = i + j;
if (result == solution) {
cout << "Great Job! That is the correct answer for the problem "
<< i << " + " << j << "." << endl;
cout << endl;
cout << endl;
cout << endl;
score++;
j++;
cout << endl;
}
if (result != solution) {
cout << "Oh no! " << result << " is NOT the correct answer for "
<< i << " + " << j << "." << endl;
wrong = wrong + 1;
count++;
}
if (count == 3) {
cout << "The correct answer is " << i + j << "." << endl;
j++;
wrong = wrong - 3;
count = 0;
}
if (count == 1) {
cout << endl;
count--;
wrong = wrong - 1;
}
if (count == 2) {
cout << endl;
count--;
wrong = wrong - 2;
}
}
if (j == 13) {
system("pause");
correct = score - wrong;
score = (correct * 100) / 13;
}
if (score >= 80) {
cout << "Excellent!!!!!" << endl;
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "Keep up the good work." << endl;
} else if (score >= 70) {
cout << "Congratulations!!!!!" << endl
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "Let's see if we can score even higher next time." << endl;
} else {
cout << "You scored below 70 which means that you may need some"
<< " more practice." << endl;
cout << "You scored " << score << "%." << endl;
cout << "You got " << correct << " out of 13 correct." << endl;
cout << "You might want to try the " << i << " facts again."
<< " Goodluck!!!!!" << endl;
}
}
} catch (char fact) {
cout << "Invalid input. You can only enter (m)ultiplication or"
<< " (a)ddition. Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
} catch (int i) {
cout << "Invalid input0. You can only enter a
number here. Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
} catch (...) {
cout << "Invalid input2. You can only enter a number here.
Please try again." << endl;
cin.clear();
cin.ignore(100, '\n');
}
} while (!done);
return 0;
}
The task is quite hard, but if you dare trying, I suggest doing it in two steps:
Implement inaccurate solution: timer expiration is checked between queries to user.
If there is some time left, next question is asked, otherwise statistics is shown. So program always waits for user input on the last question despite timer has run out. Not what exactly quizzes look like, but good move to start with.
Method: before starting quiz save current time, before each question take delta between saved time and current one and compare with time limit. Example with chrono (starting from C++11), example with oldschool clock
Add middle-question interruption
This part requires function, which will wait for user input not longer, than specified amount of time. So instead of using std::cin() you'll need to calculate amount of time left (time limit minus delta between cur time and start time) and call some sort of cin_with_timeout(time_left).
The hardest thing is implementing cin_with_timeout(), which requires solid knowledge of multithreading and thread synchronization. Great inspiration can be found here, but it is direction to start thinking rather than complete solution.

C++ only 2 loop iterations

I'm studying at university and we started programming in C++. I had some basic concepts about Java (variables, loops and more easy things) and I tried to practice on my own with Microsoft Visual Studio, but I had a problem, this is my code, is a program that tries to guess the number you are thinking of.
void main(){
srand(time(NULL));
int number=1+rand()%100;
int highLow;
bool a;
a = true;
cout << "Think a number between 1 and 100 and I will guess it" << endl;
system("PAUSE");
cout << "\nIs it ";
cout << number;
cout << "?" << endl;
cout << "If the number is lower press 1, higher 2 and correct 3" << endl;
cin >> highLow;
while (a)
{
if (highLow == 1)
{
number = 1 + rand() % number;
cout << "\nIs it ";
cout << number;
cout << "?" << endl;
cin >> highLow;
}
else if (highLow == 2)
{
number = rand() % (100 - number+1)+number;
cout << "\nIs it ";
cout << number;
cout << "?" << endl;
cin >> highLow;
}
else if (highLow == 3)
cout << "I win this time" << endl;
a = false;}
}
The problem is that it should ask the user as many times as needed to guess the number, but it only does 2 times, then stops. Can you help me please?
If only you had indented your code properly…
The last a = false; statement executes no matter what, because it's outside the scope of the last else if statement. Basically, this:
else if (highLow == 3)
cout << "I win this time" << endl;
a = false;
means the following:
else if (highLow == 3) {
cout << "I win this time" << endl;
}
a = false;
You need to add some curly braces where appropriate.

While loops expression

I'm trying to write a program that asks the user to enter digits between 0 and 1000000 and it outputs the occurrence of a certain number (that the user entered as well)
I've wrote this program and I believe it works well, but I have one issue which is if the while expression is not true, I want to cout a certain message but I don't know where to place it.
Here's my program:
#include <iostream>
using namespace std;
int main()
{
int n,j=0,key;
cout << "Pleaser enter digits\n";
cin >> n;
cout << "please enter key number\n";
cin >> key;
while (n>0 && n<1000000)
{
if(n%10==key)j++;
n= n/10;
}
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
Thanks in advance!
Use
if(n>0 && n<1000000)
{
while(n)
{
if(n%10==key)
j++;
n= n/10;
}
}
else
cout<<"n is supposed to be between 0 and 1000000";
As there are no breaks (or no other piece of code that can jump) inside the bucle, everything after the while structure is executed because the expression returned false.
while (n>0 && n<1000000)
{
if(n%10==key)j++;
n= n/10;
}
cout << "While expression not anymore true" << endl;
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
UPDATE
Based on the comments, it seems that you want to check if the number entered is valid or not. Simply, just check it before the while:
if(not (n>0 and n<1000000)) cout << "Number must be between 0 and 1000000" << endl;
else {
while (n)
{
if(n%10==key)j++;
n= n/10;
}
}
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
Write a if statement before while loop.
if(!(n>0 && n<1000000))
{
cout << "....";
return -1;
}
while(..)

how do I continue on the function without exiting after else statement in c++

Hello so my question is how do I continue on with new inputs after an else statement? In my program, I wrote an else statement that if the input is neither 1 nor 2, the user has to put a new value to get the result he/she wants. But after my else statement, my program shuts down. I don't know how to fix this. I'm very new to c++ so please keep harsh comments to yourself...
Here's my code:
// This program will allow the user to input from the keyboard
// whether the last word to the following proverb should be party or country:
// "Now is the time for all good men to come to the aid of their _______"
// Inputting a 1 will use the word party. A 2 will use the word country.
#include <iostream>
#include <string>
using namespace std;
void writeProverb(int);
int main ()
{
int wordCode;
cout << "Given the phrase:" << endl;
cout << "Now is the time for all good men to come to the aid of their ___" << endl;
cout << "Input a 1 if you want the sentence to be finished with party" << endl;
cout << "Input a 2 if you want the sentence to be finished with country." << endl;
cout << "Please input your choice now" << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
return 0;
}
void writeProverb (int number)
{
if (number == 1)
cout << "Now is the time for all good men to come to the aid of their party." << endl;
else if (number == 2)
cout << "Now is the time for all good men to come to the aid of their country." << endl;
else
{
cout << "I'm sorry but that is an incorrect choice: Please input a 1 or 2" << endl;
}
}
So basically, after the else statement, I want my program to wait for the user to enter 1 or 2 instead of just shutting down.
do {
cout << "Please input your choice now" << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
}while (wordCode != 1 && wordCode != 2);
This code exits if user inputs 1 or 2. Stays otherwise.
You want to have a do-while construct until you get a legal value, as Sakthi Kumar already pointed out.
However, you do not want to move the knowledge of what a legal value is up to main. Therefore, have the writeProverb method return if the value is legal or not. This keeps things in the proper abstraction level. You should also consider updating the "menu" printing by using an object, thus tying everything together.
// ... in main()
do {
cout << "Please input your choice now" << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
} while( !writeProverbIfLegalNumber(wordCode) );
}
bool writeProverbIfLegalNumber (int number) {
if (number == 1) {
cout << "Now is the time for all good men to come to the aid of their party." << endl;
return true;
}
else if (number == 2) {
cout << "Now is the time for all good men to come to the aid of their country." << endl;
return true;
}
else
{
cout << "I'm sorry but that is an incorrect choice: Please input a 1 or 2" << endl;
}
return false;
}
This is basic logic, you should read about loops and how to use them. This while loop continues while wordCode is not between 1 and 2 inclusive; in other words, it continues until you get 1 or 2.
int main ()
{
int wordCode;
cout << "Given the phrase:" << endl;
cout << "Now is the time for all good men to come to the aid of their ___" << endl;
cout << "Input a 1 if you want the sentence to be finished with party" << endl;
cout << "Input a 2 if you want the sentence to be finished with country." << endl;
do
{
cout << "Please input your choice now 1 or 2: " << endl;
cin >> wordCode;
} while(!(1 <= wordCode && wordCode <=2));
cout <<endl;
writeProverb(wordCode);
return 0;
}
in this case,you can put the judging statement in the "main" function. You can use a "while" statement to control the logic.
boolean flag = true;
while(flag){
cout<<"input";
cin>>wordCode;
if(wordCode==1 || wordCode==2){
flag=false;
writeProverb(wordCode);
}
}