c++ task won't execute after while loop - c++

C++ newbie here. I'm not sure how to describe this but the task outside of the while-loop won't execute immediately. I need to enter the input value again to get it done.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int fourDigitInt, firstDigit, secondDigit, thirdDigit, fourthDigit, i = 0;
cout << "Enter a 4-digit integer : ";
cin >> fourDigitInt;
while (fourDigitInt > 9999 || !(cin >> fourDigitInt))
{
i++;
if (i >= 3)
{
cout << "You do not seem to understand the program instruction.\nPlease try again later." << endl;
return -1;
}
else
{
cout << "Error: Please make sure you are entering a 4-digit integer" << endl;
cin.clear();
cin.ignore(4, '\n');
cout << "Enter a 4-digit integer : ";
}
}
firstDigit = fourDigitInt / 1000 % 10;
secondDigit = fourDigitInt / 100 % 10;
thirdDigit = fourDigitInt / 10 % 10;
fourthDigit = fourDigitInt / 1 % 10;
cout << "1st digit : " << firstDigit << endl;
cout << "2nd digit : " << secondDigit << endl;
cout << "3rd digit : " << thirdDigit << endl;
cout << "4th digit : " << fourthDigit << endl;
}
Here are some problems I encountered:
1)If I enter a string first, it doesn't have any problem.
2)But if I enter any number less than 9999, it won't execute the calculation unless I
enter it again.
3)If I enter a 5-digit number the endl won't work. It will just display Enter a 4-digit integer : Error: Please make sure you are entering a 4-digit integer which suppose to be a different line.
Where exactly did I do wrong? Thank you in advance.

The main issue here is in the while loop condition. It should just check for the value of the fourDigitInt variable as that is what is important.
Looking closer, you will also be able to notice the fact that the if case inside of the loop would check for the second iteration instead of the third. I fixed that as well by moving the i++ inside of the else block.
while (fourDigitInt > 9999 || fourDigitInt < 1000) {
if (i >= 3) {
cout << "You do not seem to understand the program (ironic coming for OC) instruction.\nPlease try again later." << endl;
return -1;
}
else {
i++;
cout << "Error: Please make sure you are entering a 4-digit integer" << endl;
cout << "Enter a 4-digit integer : ";
cin >> fourDigitInt;
}
}
Any other issues with your code that may occur are not related to this question.

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...
}

How do I validate user input with c++?

Hey so this is really getting on my nerves.
I'm trying to validate user input within a loop.
I need the user input to be between 0 and 60. I can validate it no problem but what I want it to do is re-ask the previous question if the input is incorrect, you know? like repeat the loop if that makes sense
int main()
{
//Constants
const int MAXROUNDS = 4;
const int NUMARCHERS = 3;
//Variables
int archerNum;
int roundNum;
double score;
double total;
//Start of outer loop, this loop displays each Archer
for (archerNum = 1; archerNum <= NUMARCHERS; archerNum++)
{
total = 0; //This clears the total for the archer
//Start of second loop, this loop displays each round
for (roundNum = 1; roundNum <= MAXROUNDS; roundNum++)
{
cout << "Enter Round " << roundNum << " score for Archer "
<< archerNum << ": ";
cin >> score;
if (score < 0 | score > 60)
{
cout << "ERROR! Number must be between 0 and 60!";
}
}
total = score + score + score + score; //This calculates the total score for the tournament
cout << "\nThe total score for archer " << archerNum << " is: "
<< total << "\n\n";
}
return 0;
}
This is my code ^
Now I have tried so many things. I've looked through my textbook and I've googled everything but I cant seem to find the answer.
I've tried putting the error message in a do-while loop
i've used if-else statements
i've used while loops
I think I've literally used every different type of loop there is and I still cant seem to figure it out and I'm becoming very frustrated.
Thanks in advance
Here is a simple version of just the number input and error message:
//#include "pch.h" if using Visual Studio 2017
#include <iostream>
using namespace std;
int main(){
cout << "Please enter a number between 0 and 60." << endl;
int input;
cin >> input;
while(input < 0 || input > 60 || cin.fail()){ //Using cin.fail() here in case the user enters a letter or word
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cerr << "Number must be between 0 and 60. Please try again." << endl;
cin >> input;
}
return 0;
}`
Alternatively, you could use a goto statement though, as I am sure many others on this site will tell you, that is not recommended as it leads to the infamous 'spaghetti code'.
Simply add roundNum -= 1; inside the validation If statement. It will make the counter decreased by 1, and re-ask the previous question
//Start of second loop, this loop displays each round
for (roundNum = 1; roundNum <= MAXROUNDS; roundNum++)
{
std::cout << "Enter Round " << roundNum << " score for Archer "
<< archerNum << ": ";
std::cin >> score;
if (score < 0 || score > 60)
{
std::cout << "ERROR! Number must be between 0 and 60!"<<endl;
roundNum -= 1; //or roundNum--
}
}
Try:
bool inputError;
do {
inputError = false;
std::out << "Enter Round "
<< roundNum
<< " score for Archer "
<< archerNum << ": ";
if (std::cin >> score) {
if (score < 0 || score > 60)
{
std::cout << "ERROR! Number must be between 0 and 60!";
inputError = true;
}
}
else {
std::cout << "ERROR! Your input must be a number";
inputError = true;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
} while(inputError == true);

Guess the random number game

I am making a number guessing game and I do not know how to incorporate a certain number of guesses the users has to get the correct answer. I want the user to have only 3 guesses to guess the number but after 3 guesses, they lose if they do NOT get it correct. Here is my code below:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand ( time(NULL) );
cout << "Select a difficulty: 1) Easy, 2) Medium, 3) Hard " << endl;
int userlevel;
int userinput;
int randomNumber;
cin >> userlevel;
{
if (userlevel==1)
cout << "You chose Easy: 3 chances to guess correctly" << endl;
cout << "Pick a number between 1 and 10: " << endl;
cin >> userinput;
randomNumber = rand() % 10 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
{
if (userlevel==2)
cout << "You chose Medium: 4 chanaces to guess correctly" << endl;
cout << "Pick a number between 1 and 50: " << endl;
cin >> userinput;
randomNumber = rand() % 50 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
{
if (userlevel==3)
cout << "You chose Hard: 5 chances to guess correctly" << endl;
cout << "Pick a number between 1 and 100: " << endl;
cin >> userinput;
randomNumber = rand() % 100 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
return 0;
}
You should look into while-loops. It would be used like this:
int main() {
//...everything above this in yours is good
int Number_to_guess = (rand() % 10 + 1);
int NChances = userlevel + 2;
cout << "You have " << NChances << " chances to guess right.\n";
while (NChances != 0)
{
cout << "Guess: ";
cin >> userinput;
if (userinput == Number_to_Guess) {
cout << "You win! Congrats!\n";
break; // this will break out of the while-loop
}
NChances--; // this will count down the chances left
}
if (NChances == 0) {
cout << "Sorry, you lose. Try again next time!\n";
}
return 0;
}
The main think you're missing here is a loop around the guess limit. So after you figure out what level they are, you can say something like the following pseudocode:
While (counter <= 3)
*Your If Statements*
counter = counter +1
Make sure that in the if statement where they guessed the number right, you break them out of the loop early.
Finally, it might make more sense to guess a number before you enter the loop. So, something like they pick the difficulty, the random number is picked depending on what they say, and then the loop begins. The way it is now, a new random number will be created each time through the loop. I'm not sure if that's intended.

How do you make a counter to count the number of even and odd numbers entered by user?

I have this code so far that is supposed to keep asking the user for a number until they type 0. Then the program will tell the user how many odds and evens they typed. I cannot get the latter function to work correctly. Any tips? I am a beginner, so please no advanced ways to solve this :D
#include <iostream>
using namespace std;
int main ()
{
int n;
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
return 0;
}
A couple things:
Code indentation (or lack thereof) makes this really hard to read. Indentation is not only cosmetic, but can help in understanding code.
You are setting the counter variables to zero each time the loop runs. Declare them outside of the loop so they retain their values.
The else clause of the if statement has erroneous syntax. Use a simple else instead, as there are only two cases for the parity of n.
When the user types 0 to exit the loop, it too is counted as an even integer. Add a condition in the if statement to account for this.
Applying these changes yields this code:
int n;
int myCounter1 = 0, myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do {
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0 && n != 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
} while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
This
else n == 0
{
myCounter2++;
}
should be
else
{
myCounter2++;
}
Honestly, I don't even know why it didn't grab your attention, since it can't compile.
Also, you shouldn't set the counters to zero in the loop. So
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
should be
int myCounter1=0, myCounter2=0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
And, finally, since you probably shouldn't count the 0 as one of the integers entered...
cout << "You entered " << myCounter1-1 << " even numbers, and " << myCounter2 << " odd numbers " << endl;
You have 2 bugs and 1 syntax error.
line:else n == 0 should be simply else
The 2 bugs are related to your counters:
1) You have to exclude the 0 input from the counters.
2) Every time you are reading a number your are setting them (the counters) to zero, which means that you will always ending with zero and one.
Here it is for anyone interested:
include
using namespace std;
int main ()
{
int n;
int myCounter1 = 0;
int myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter2 << " odd numbers, and " << myCounter1-1 << " even numbers " << endl;
return 0;
}

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(..)