Random letter generator game [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Warning: I am brand new to programing! I am trying to create a random letter generator game for a class project. I feel like I have a decent start to it but I am having difficulty with a few points.
The program is supposed to ask the player how many games they would like to play(1-5). The maximum number of guesses they get per game is 5 and then it is supposed to print out what the correct answer was if it was not guessed. As it is, I have it so that it will run the correct number of guesses but not games and it dosent cout<< the correct answer when all guesses are done. Any help is appreciated, thanks.
#include<iostream>;
#include<cstdlib>;
#include<ctime>;
using namespace std;
int main()
{
char alphabet [27];
int number_of_games;
char guess;
int x = 1;
srand(time(0));
int n = rand() % 26 + 1;
cout<<"Weclome to the Letter Guessing game!\n";
cout<<"You have 5 chances to guess each letter.\n \n";
cout<<"How many games do you want to play?\n";
cin >> number_of_games;
cout<<"**************************************************\n\n";
while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
if (number_of_games < 1)
{
cout<< "Lets play game " << number_of_games << '\n';
}
//cout << (char)(n+97); //cheat to make sure working
cout<<"Enter your guess: ";
cin >> guess;
int guessValue = int(guess);
if (guessValue > (n+97))
{
cout<<"The letter you are trying to guess is before " <<guess <<"\n";
}
else if (guessValue < (n+97))
{
cout<<"The letter you are trying to guess is after " <<guess << "\n";
}
else if( (char)(n+97))
{
cout << "The answer you were looking for was " << (char)(n+97) << "\n";
}
else
{
cout<<"Your guess is correct! \n";
break;
}
//if answer is not right after x tries, cout the correct answer
x++;
}
system("pause");
return 0;
}

You can use "nested loops" - an outer loop for games, and an inner loop for turns. I've used a for loop in my example.
Also, no need to convert everything to int. char is an integral type and can be used just like a number:
while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
// Select a new char (a-z) for each game
char n = 97 + rand() % 27;
cout << "Lets play game " << x << '\n';
// 5 guesses
for (int number_of_guesses = 0; number_of_guesses < 5; number_of_guesses++) {
cout << "Enter your guess: ";
cin >> guess;
if (guess > n)
{
cout << "The letter you are trying to guess is before " << guess << "\n";
}
else if (guess < n)
{
cout << "The letter you are trying to guess is after " << guess << "\n";
}
else
{
cout << "Your guess is correct! \n";
// Break out of the inner for loop, not the while
break;
}
}
x++;
}

Related

_sleep() function not working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I get the error:
'_sleep': This function or variable has been superceded by newer
library or operating system functionality. Consider using Sleep
instead. See online help for details.
Can you guys and/or girls tell me what library is causing this error?
Code:
// A program to keep track of points and time and to give a random letter for the game scattergories
#include<iostream>
#include<ctime>
#include<string>
using std::cout;
using std::cin;
using std::string;
using std::getline;
void ltr() //gives a random letter
{
srand(time(NULL)); //gives a differant pattern every time
char letter;
letter = rand() % 27 + 64; //assigns a random letter in ascii code to a char (resulting in a random letter)
cout << "The letter is " << letter << "\n";
}
void timer()
{
cout << "You got 1.5 minutes to finish\n";
for (int i = 90; i > 0; i--)
{
if (i % 5 == 0)
cout << i << "\n";
_sleep(1000);
}
cout << "DING DONG!!! DING DONG!!! Time's up!!!\n";
}
void table()
{
int plr, ctr;
string lst[5][20]; //first dimantion: how many players. second dimantion: how many catagories, third dimantion(if added) will be the round
cin >> plr >> ctr; //parameters for later
cin.ignore(); //To avoid the "getline" reading the last input
for (int x = 0; x<plr; x++) //the player changes only after the previus player finishes
{
timer();
for (int i = 0; i<ctr; i++) //changing catagory
{
getline(cin, lst[x][i]);
}
system("cls");
cout << "Next player\n";
}
for (int x = 0; x<plr; x++) //this part (the whole "for" loop) is for confirming
{
cout << "Player number " << x + 1 << ": ";
for (int i = 0; i<ctr; i++)
{
cout << lst[x][i] << " ";
}
cout << "\n";
}
_sleep(5000);
}
int points() //points per round
{
int a, b, c, sum;
cout << "How many sections only you got?\n"; //worth 15 points
cin >> a;
cout << "How many words only you got?\n"; //worth 10 points
cin >> b;
cout << "How many words you and another person got?\n"; //worth 5 points
cin >> c;
sum = a * 15 + b * 10 + c * 5;
return sum; //Note: It doesn't matter how many sections there are.
}
int act()
{
int Points;
ltr();
table();
Points = points();
cout << "You have earned " << Points << " this round\n\n";
return Points;
}
int main()
{
int Points;
cout << "Starting in five seconds\n";
_sleep(5000);
Points = act();
for (;;) //inf loop
{
int ph;
cout << "Press 1 to continue or anything else to stop\n";
cin >> ph;
if (ph == 1)
{
Points += act();
}
else
{
break;
}
}
cout << "You have earned a total of " << Points << " great job!";
_sleep(5000); //time to read the last text
return 0;
}
/* To do list:
*Convert to arduino
*Make timer work in background of of table
*Check if words in the table (for differant players) are the same and give points accordingly
*Check if words are actual words (connect an online dictonary?)
*Make interface? (if possible and I have time to learn how)
*Think of what to do with Hardwear
*Comment rest of the code
*/
For using Sleep() function you need
#include <windows.h>

C++ simple game using a Loop program

This program will play a game with the user, called Odds and Evens. The computer will play Evens, and the human user will play Odds. For a round of the game, each player picks an integer in the range [1,10]. The players pick their numbers independently: neither player knows the other player's number before choosing its own number. If the sum of the numbers is even, then Evens (the computer) wins that round; if the sum of the numbers is odd, then Odds (the human) wins that round. The game continues for as many rounds as the user want to play; the user ends the game by typing a non-# or a number outside [1,10] for the input. At the end of the game, the program summarizes the score.
I am having trouble properly looping this question. Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number. Also i do not know how I would have the program summarize the score. Help would be much appreciated as I have another problem for homework that is similar to this!
Here is my code:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;
bool die(const string & msg);
int main(){
srand(static_cast<unsigned>(time(0)));
unsigned num1 = 0, num = 0, sum = 0;
bool userTurn = true;
cout << "Welcome to the Odds and Evens game!";
num = rand() % 10 + 1;
while (num){
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!";
}
else {
cout << " You win!";
}
}
userTurn = !userTurn;
}
}
bool die(const string & msg){
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number.
You don't have code to re-set the value of num when it's the computer's turn.
After the line
userTurn = !userTurn;
add
if ( !userTurn )
{
num = rand() % 10 + 1;
}
Also i do not know how I would have the program summarize the score.
Keep two counters that indicate how many times the human won and how many times the computer won.
int computerWinCount = 0;
int humanWinCount = 0;
and then, update the loop to use:
if (sum % 2 == 0){
cout << " I win!";
++computerWinCount;
}
else {
cout << " You win!";
++humanWinCount;
}
The conditional of the while loop is such that your program will never terminate. Update it to something like below.
while (true) {
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
// If the user entered a number that is not
// within range or the user did not input a number,
// then break out of the loop.
if ( !cin || num1 < 1 || num1 > 10 )
{
break;
}
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!" << endl;
++computerWinCount;
}
else {
cout << " You win!" << endl;
++humanWinCount;
}
}
userTurn = !userTurn;
if ( !userTurn )
{
num = rand() % 10 + 1;
}
}
To report the summary, add the following lines before the end of the main.
cout << "Number of times I won: " << computerWinCount << endl;
cout << "Number of times you won: " << humanWinCount << endl;
Here:
num = rand() % 10 + 1;
while (num){
... // never change num
}
Do you see the problem? The computer player chooses num randomly, but only once. Just put another num = rand() % 10 + 1; inside the main loop.
(Also, you don't seem to have a way for the user to terminate the game.)
So you want a simple loop that will do the following things.
get the user input.
get the computer input
check to see who win's the current round
update scores.
this happens until the user chooses an option not from 1 to 10
after this you want to display the score.
Here is a complete example.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
int mynum, compNum, myScore(0), compScore(0);
srand(time(NULL));
cout << "Welcome to the Odds and Evens game!" << endl;
cout << "Your # in [1,10] is ";
while ((cin >> mynum) && mynum > 0 && mynum <= 10){
compNum = rand()%10 + 1;
if ((mynum + compNum)%2){
cout << "You win" << endl;
++myScore;
} else {
cout << "Computer Wins" << endl;
++compScore;
}
cout << "Your # in [1,10] is ";
}
cout << "You won " << myScore << " games" << endl;
cout << "The computer won " << compScore << " games" << endl;
return 0;
}
Your problem with the computer's number not changing is due to the fact you do not update its value within the loop.
If you want to keep track of the score, you can simply keep two integers that keep track of how many times the user has won and how many times the computer has won. Then at the end (after the while loop) cout each of their scores.
Overall your code is pretty close.
You just need to make sure you update the computer's guess inside the while loop and when you decide who's won the round increment that person's score.
The whole loop condition in your original code will always evaluate to true. As num will always be to a number 1 to 10. You'll want to use the user's input in the while loop condition.
The while condition in my code will do the following:
get the user's input. cin >> mynum will evaluate to false if cin fails to read a number. If it did read a number the condition will check to see if the number is between 1 and 10 inclusive.

Error when accessing array - stack around the variable 'scores' was corrupted [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new to C++ and have written some code in which I'm getting the following error:
Run-Time Check Failure #2 - Stack around the variable 'scores' was corrupted
What is causing this error?
Here is my code:
#include <iostream> // Enables cout and endl
#include <string>
#include <sstream>
#include "stdafx.h"
using namespace std;
int getInput();
int main()
{
int scores[5];
int i;
int j;
int numberOfScores;
for (i = 0; i < 6; i++) // Sets all 5 elements of the array to zero
{
scores[i] = 0;
}
cout << "How many scores do you have to enter?\n" << endl;
cin >> numberOfScores;
for (j = 0; j < numberOfScores; j++) // Gather test scores and increases each array index as that score is entered
{
scores[getInput()] ++;
}
cout << "The number of zeros: " << scores[0] << endl;
cout << "The number of ones: " << scores[1] << endl;
cout << "The number of twos: " << scores[2] << endl;
cout << "The number of threes: " << scores[3] << endl;
cout << "The number of fours: " << scores[4] << endl;
cout << "The number of fives: " << scores[5] << endl;
return 0;
}
int getInput()
{
int enteredScore;
cout << "Enter the test scores one at a time.\n";
cout << "The range of scores is 0 to 5.\n";
cin >> enteredScore;
if (enteredScore >= 0 && enteredScore <= 5)
{
return enteredScore;
}
else
{
cout << "Error! The range of scores is 0 to 5.\n";
cout << "Enter the test scores one at a time.\n";
cin >> enteredScore;
return enteredScore;
}
}
It seems that this declaration:
int scores[5];
Is incorrect. This creates an array with 5 numbers in it, indices from scores[0-4], however, you constantly refer to score[5], the sixth element of the array throughout your program. I recommend changing to
int scores[6];
The problem:
You are accessing your array out of bounds in several places.
Here you loop through 6 elements when you only have 5:
for (i = 0; i < 6; i++) // Loops through 6 elements
{
scores[i] = 0;
}
Here you call getInput() and use the return value as the index:
scores[getInput()] ++;
However, the first half of the function accepts inputs from the user in the range 0 to 5, thus allowing access to 6 elements:
if (enteredScore >= 0 && enteredScore <= 5)
It gets even worse if the user enters a number outside that range, as they are then given a second opportunity to enter a number, only this time there is no validation and any number they enter is accepted:
cin >> enteredScore;
return enteredScore;
Finally, you again attempt to access a 6th element here:
cout << "The number of fives: " << scores[5] << endl;
Solution:
First, you need to do one of two things:
Change the for loop, if statement, and cout statements so that they do not access index 5
or:
Create the array so that it has 6 elements: int scores[6];
Secondly, you need to fix the bug in your getInput() function so that it validates the input properly. You could try this for example:
int getInput()
{
int enteredScore;
cout << "Enter the test scores one at a time.\n";
cout << "The range of scores is 0 to 4.\n";
cin >> enteredScore;
while (enteredScore < 0 || enteredScore > 4)
{
cout << "Error! The range of scores is 0 to 4.\n";
cout << "Enter the test scores one at a time.\n";
cin >> enteredScore;
}
return enteredScore;
}
You have an error in
cout << "The number of fives: " << scores[5] << endl;
Your array is of size 5 but you are accessing the 6th element.
Same with for (i = 0; i < 6; i++) should be i < 5.

How do I use cin in a while loop?

I'm trying to get the user to input their name(s) using a while loop with an array and cin, but after the last person's name is input, the program crashes instead of moving on. Is there a way to fix this, or do I need to completely change up the code? I'm also fairly new to c++, so can any answers be given as simply as possible?
#include <iostream>
#include <string>
using namespace std;
int main()
{
unsigned int numberofplayers;
number://loop back here if more than 4 players
cout << "Number of players: ";
cin >> numberofplayers;
if(numberofplayers > 4 || numberofplayers < 1){
cout << "Invalid number, please enter a number from 1 to 4." << endl;
goto number;
}
string name[numberofplayers];
cout << "Enter your name" << endl;
int a = 1;
while(a < numberofplayers + 1){
cout << "Player " << a << ": ";
cin >> name[a];
cout << "Hello, " << name[a] << "." << endl;
a++;
}
}
You would probably facing array index out of bound, so Change you while loop to this and set a=0 to fill from 0th index.
while(a < numberofplayers){
}
Your last iteration exceeds the size of the array. You need to change it to
while(a < numberofplayers)
also, on another note, the keyword goto isn't used much anymore. I would suggest using a while there also like
while(true){
cout<<"number of players";
cin>>numberofplayers
if(numberofplayers is valid input){
break;
}
cout<<"bad input";
}
There is a question on stackoverflow discussing the use of goto extensively here:
GOTO still considered harmful?

I've know idea where to look, maybe it's an infinite loop? (C++, using VS2012) [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Well, I'll introduce myself first. I'm Ben, a 17-years old 'game-programmer' from the Netherlands who just has begun to program in C++ (started about a month ago, but programming for a year right now) (and I'm using Microsoft Visual Studio 2012 as compiler). Now, I am 'learning it myself' but I still do use a book and that book is called 'Beginning C++ Through Game Programming, Third Edition' by Michael Dawson.
I just did finish with chapter two and the last excersize was: "Write a new version of the Guess My Number program in which the player and the computer switch roles. That is, the player picks a number and the computer must guess what it is."
Here follows the code of the 'Guess My Number' Program:
// Guess My Number
// The classic number guessing game
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0))); //seed random number generator
int secretNumber = rand() % 100 + 1; // random number between 1 and 100
int tries = 0;
int guess;
cout << "\tWelcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
if (guess > secretNumber)
{
cout << "Too high!\n\n";
}
else if (guess < secretNumber)
{
cout << "Too low!\n\n";
}
else
{
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
}
} while (guess != secretNumber);
return 0;
}
Now, I was busy with thinking, programming testing and it just wouldn't work.
It seems I got stuck with such a infinite loop. But I can't find the problem.
Here's the code, and other ways to fix this are welcome, just keep in mind that I don't know a lot of the language. ;)
// Guess My Number 2
// The classic number guessing game with a twist
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
int secretNumberComputer = rand() % 100 + 1;
int secretNumberPlayer;
int triesPlayer = 0;
int triesComputer = 0;
int guessPlayer;
int guessComputer;
int tooHighPlayer;
int tooLowPlayer;
int correctPlayer;
int tooHighComputer;
int tooLowComputer;
int correctComputer;
int selectNumberIncorrect;
int lowerGuessComputer = 101;
int higherGuessComputer = 0;
cout << "Welcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guessPlayer;
++triesPlayer;
tooHighPlayer = (guessPlayer > secretNumberComputer);
tooLowPlayer = (guessPlayer < secretNumberComputer);
correctPlayer = (guessPlayer == secretNumberComputer);
if (tooHighPlayer)
{
cout << "Too high!\n\n";
}
else if (tooLowPlayer)
{
cout << "Too low!\n\n";
}
else if (correctPlayer)
{
cout << "\nThat's it! You got it in " << triesPlayer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctPlayer);
cout << "Now it's time for you to pick a number and then the computer will guess.\nEnter a number between 1 and 100: ";
do
{
cin >> secretNumberPlayer;
selectNumberIncorrect = (secretNumberPlayer > 100 || secretNumberPlayer < 1);
if (selectNumberIncorrect)
{
cout << "\nHey, that isn't a number between 1 and 100! Please pick a number that is: ";
}
else
{
break;
}
} while (selectNumberIncorrect);
guessComputer = (rand() < lowerGuessComputer && rand() > higherGuessComputer);
cout << "\n\nNow the computer is going to try to guess your number:" << endl;
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
tooHighComputer = (guessComputer > secretNumberPlayer);
tooLowComputer = (guessComputer < secretNumberPlayer);
correctComputer = (guessComputer == secretNumberPlayer);
lowerGuessComputer = (rand() % 100 + 1 && rand() < guessComputer);
higherGuessComputer = (rand() % 100 + 1 && rand() > guessComputer);
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
}
else
{
cout << "Error, check code!\n\n";
}
do
{
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctComputer);
if (triesComputer < triesPlayer)
{
cout << "You lost against the computer!\n\n";
}
else if (triesComputer > triesPlayer)
{
cout << "You won!\n\n";
}
else
{
cout << "It's a tie!\n\n";
}
cout << "Thank you for playing! Goodbye!" << endl;
return 0;
}
In this block you aren't checking the computer's guess for correctness (assigning correctComputer), so the loop continues forever, unless it guessed correctly the first time.
do
{
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctComputer);
Your second do loop never recalculates the computer's guess.
i.e. you have the computer guess one number before the do loop, then in the loop you keep checking if that one guess is too high or too low, never recalculating its value. It'll obviously never end.
You need to do the computer's guess calculation inside the second loop.
EDIT
Also, this logic is incorrect:
lowerGuessComputer = (rand() % 100 + 1 && rand() < guessComputer);
higherGuessComputer = (rand() % 100 + 1 && rand() > guessComputer);
The guess will always be 0 or 1 because the result of the right-hand-side operation is a boolean. In fact, I don't know what you're trying to do there. You're performing && between an integer and a boolean. I also don't understand why you are calculating two different guesses - you should calculate one number within the range of the higher/lower parameters you were given.
In addition to what Kevin Tran wrote, please check the valid input type for cin.
Imagine someone typing characters instead of integers.
so
cin >> guessPlayer;
can be written as
if (cin >> guessPlayer) {
// Do you logic here
}
else {
cout<<"Enter numbers only. :)";endl;
continue;
}
Hope this helps.
Instead of analyzing the code you posted which has numerous flaws, let's just think about what your program has to do: The user will pick a random number, and the computer will try to guess that number.
So, your program flow should go like this:
The computer picks a random number. It prints it out and asks the user to choose if the number is too high, too low or correct. (i.e. by asking the user to type '1' if too high, '2' if too low or '3' if it's right).
If the user types '3' then obviously you're done.
If it's too high, the computer picks a new random number (smaller than it's last guess) and tries the above logic again.
If it's too low, the computer picks a new random number (greater than it's last guess) and tries the above logic again.
Now let's try and implement some code that implements the above:
using namespace std;
int main()
{
int range_low = 0; // The number the user picked is greater than this
int range_high = 100; // The number the user picked is smaller than this
srand(static_cast<unsigned int>(time(0)));
do
{
// We want to generate a random number between range_low and range_high. We do this
// by generating a random number between zero and the difference of "low" and "high"
// adding it to low and adding one more.
int guess = range_low + ((rand() % (range_high - range_low)) + 1);
cout << "I'm guessing your number is " << guess << "... how did I do?" << endl
<< " [1: too high, 2: too low, 3: you got it!] ";
// Now let's see how we did...
int choice;
cin >> choice;
if(choice == 3)
{
cout << "Be amazed at my psychic powers! For I am a computer!" << endl;
break;
}
if(choice == 2)
{
cout << "Hmm, ok. I was sure I had it. Let's try again!" << endl;
range_low = guess;
}
if(choice == 1)
{
cout << "Really? Ok, ok, one more try!" << endl;
range_high = guess;
}
} while(true);
return 0;
}
Here are two exercises for you to improve the above:
First, try to compare the logic of this code against the logic of your code and see where your code differs - try to understand why it was wrong. It will help to try to execute the program using pen and paper, just like you were a computer that understood C++.
Second, try to add code to ensure that the computer never guesses the same number twice.