C++ Random Number Guessing Game Errors - c++

So, I have to write a program from a random guessing game. The program needs to ask the player to guess a number between 1-100. At least one function must be used. It needs to tell the player if they are too low/high, ask them to try again, or if they guess it, ask them to play again.
I have a few errors that I can not figure out.
44: error: ‘int winlose’ redeclared as different kind of symbol
9: error: previous declaration of ‘int winlose(int)’
44: error: ‘g’ was not declared in this scope
Code
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int winlose(int);
int main()
{
int g, n, x;
while (x!=0)
{
do
{
srand(time(NULL));
n = 1 + rand()%100;
cout<<"Welcome to the guessing game. I have a number between 1-100.
Can you guess it?"<<endl;
cout<<"Please enter your guess"<<endl;
cin>>g;
winlose(g);
} while (n!=0);
cout<<"Play again? Enter 0 for no, any other number for yes."<<endl;
cin>>x;
}
return 0;
}
int winlose(g)
{
if (g<n)
{
cout<<"Your guess is too low. Try again."<<endl;
cin>>g;
}
else if (g>n)
{
cout<<"Your guess is too high. Try again."<<endl;
cin>>g;
}
else (g=n)
{
cout<<"Congrats! You win. The number was "<<n<<endl;
n=0;
}
return g;
return n;
}

You made a few mistakes in addition to the function declaration.
Function declarations must contain the type of each parameter, so the correct way is:
int winlose(int g);
You cannot use a condition in an else statement: (else (g=n)). An else statement is a catch-all, if none of the previous conditions (the ones in the if and else if()'s) were met. If you only want this to trigger on a specific condition, use another else if(). You are not required to have an else at the end of every if statement; it is perfectly correct to end with an else if(){...}.
You also need to compare with '==' rather than '='. = is the assignment operator and g=n will set the value of g to n. If you want to check if g is equal to n, you will have to use g==n
You should call srand() in the outer loop, otherwise after every guess, value changes.
The rest is corrected and sometimes slightly changed for correct performance:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
bool winlose(int number, int givenNumber);
int main(){
int g, n, x;
bool guessed;
do {
srand(time(NULL));
n = 1 + rand()%100;
cout<<"Welcome to the guessing game. I have a number between 1-100. Can you guess it?"<<endl;
do {
cout<<"Please enter your guess"<<endl;
cin>>g;
guessed = winlose(g, n);
} while (!guessed);
cout<<"Play again? Enter 0 for no, any other number for yes."<<endl;
cin>>x;
} while (x!=0);
return 0;
}
bool winlose(int g, int n) {
if (g<n) {
cout<<"Your guess is too low. Try again."<<endl;
return false;
}
else if (g>n) {
cout<<"Your guess is too high. Try again."<<endl;
return false;
}
else {
cout<<"Congrats! You win. The number was "<<n<<endl;
return true;
}
}

Related

While loop and do while loop only running once in a calculator program. C++

Was trying to run a simple calculator using a while loop and internal class. My issue is that I used a while loop that had the condition that when a boolean called flag is equal to true it would continually run the program over and over. To exit the while loop I included a section to ask the user if it wanted to continue and allowed them to input a value to the flag. No matter how many different versions of the conditions I use the loop only runs with once. I currently have a do while loop that checks if an int called loop is less than 2 which is initialized to have the value of 1. After presenting the value it increments int loop so that it is 2 and doesn't meet the loop requirements. Then asks the user if they want to continue, which if true resets the value to 1. Still hasn't worked and nothing online has shown the same issue or a solution, even in different languages. Thank you to any additions.
Code: (C++)
// main.cpp
// Calculator
//
// Created by yared yohannes on 12/10/21.
//
class calculation{
public:
calculation(){
}
int add(int first, int second){
int result= first+second;
return result;
}
int minus(int first, int second){
int result= first-second;
return result;
}
int multi(int first, int second){
int result= first*second;
return result;
}
int divide(int first, int second){
int result= first/second;
return result;
}
};
#include <iostream>
using namespace std;
int main(){
int first=0,second=0;
bool flag=true;
char sign;
int loop=1;
calculation calc;
cout<<"Welcome to the calculator program.\n";
do{
cout<<"Please enter the first value: ";
cin>>first;
cout<<"Please enter the desired operation(+,-,*,/): ";
cin>>sign;
cout<<"Please enter the second value: ";
cin>>second;
if(sign=='+'){
cout<<calc.add(first, second)<<"\n";
}
else if(sign=='-'){
cout<<calc.minus(first, second)<<"\n";
}
else if(sign=='*'){
cout<<calc.multi(first, second)<<"\n";
}
else if(sign=='/'){
cout<<calc.divide(first, second)<<"\n";
}
cout<<"Do you want to continue(true or false): ";
cin >> flag;
loop++;
if(flag==true){
loop=1;
}
}while(loop<2);
}
In C++ bools are stored as 0 or 1 values. 0 is false and 1 is true. If you're putting in "true" for the cin statement it won't work so loop will always increase. What you have to do is put in 0 or 1 into the console. You could also store the input as a string and use if statements to check if it is "true" or "false" and set the boolean value based on that. Like this:
#include <string>
/*
The code you have
*/
int main() {
string booleanInput;
//Code you have
cin >> booleanInput;
if(booleanInput == "true") {
flag = true;
} else if(booleanInput == "false") {
flag = false;
}
//Other code you have
}

Random number generator game

#include <iostream>
#include <stdlib.h>
using namespace std;
void Guess(int Answer,int guess)
{
if(guess!=Answer)
{
if(guess<Answer && guess!=Answer)
{
cout<<"The number is higher, try again"<<endl;
cin>>guess;
}
else
if(guess>Answer && guess!=Answer)
{
cout<<"The number is lower, try again"<<endl;
cin>>guess;
}
}
}
int main()
{
int Answer,guess;
Answer=rand()%100;
cout<<Answer<<endl;
cout<<"Guess the number from 1 to 100"<<endl;
cin>>guess;
while(Answer!=guess)
{
Guess(Answer,guess);
if(Answer==guess)
break;
}
if(guess==Answer)
cout<<endl<<"Congratulations, you guessed the number, it was "<<Answer<<" !";
}
So, this is the code I made after I learned some basic functions, you can probably tell that it is supposed to generate a random number, and then you have to guess what the number is, but I have a few problems:
it generates the same random number
If you don't guess it right the first time, the code keeps going forever even if at some point u guess the number.
If you guess a higher number, let's say 50 and the answer if 40, even if u then guess 30 it still says the number is lower when it's supposed to say higher.
What did I do wrong?
Changed void Guess(int Answer,int guess) to void Guess(int& Answer,int& guess) and added srand ( time(NULL) ); at the start of int main to prevent the same number to be generated

C++ code compiles but doesn't run [closed]

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 6 years ago.
Improve this question
I am currently writing a Texas Hold'em code in order to learn more about c++ and gain experience. But I recently ran into a problem in which I have no idea what to do.My code compiles just fine without errors but once I make it run and it arrive at a specific function it just stops working (as in I get an error from CodeBlock saying your program has stopped working). I have tried cutting out parts such as loops in the function to see which specific part is the problem but after a couple of days im still at a stop.
Here is the function and class that I believe is the problem:
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
Here is the full code in case I am wrong of the source of the problem:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
using namespace std;
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
cin>>i;
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
player[0].card_generator();
max_i = i;//max_i is nb of players
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
void Player::card_generator(){
string card_value[13];
card_value[0]="1";
card_value[1]="2";
card_value[2]="3";
card_value[3]="4";
card_value[4]="5";
card_value[5]="6";
card_value[6]="7";
card_value[7]="8";
card_value[8]="9";
card_value[9]="10";
card_value[10]="J";
card_value[11]="Q";
card_value[12]="K";
string card_type[4];
card_type[0]="of hearts";
card_type[1]="of diamonds";
card_type[2]="of clubs";
card_type[3]="of spades";
string card[53];
int x=0;
fill_n(card,53,0);
for (int j=0;j<4;j++){
for (int q=0;q<13;q++){
card[x]=card_value[q]+" "+card_type[j];
cards[x]=card[x];
x++;
}
}
}
If you have any criticism about the code itself even if not directly linked to problem feel free to tell me as I'm doing this to learn :D. Thank you in advance!!
#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
Be consistent in what you do. Including <stdlib.h> and <ctime> looks strange. Either include <cstdlib> and <ctime>, or include <stdlib.h> and <time.h>.
using namespace std;
Don't do this. This using imports all names from the std namespace, which is several hundreds. Only import those names that you actually need, or, alternatively, write std::time instead of the unqualified time. This makes it perfectly clear that you are referring to the time from the standard library instead of one that you might have defined yourself.
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
The cards should not be represented as strings, but as a separate data type called Card, with properties like suit and rank and a to_string method.
public:
void set_name(string a){name=a;}
To make your program fast, pass a as const std::string & instead of a simple string. This will prevent some copying of data. You should give a better name to the parameter, e.g. void set_name(const std::string &name) { this.name = name; }.
string print_name(){return name;}
This method does not print anything, therefore it must not be called print_name.
void card_generator();
Methods usually are named with verbs, not with nouns. So generate_cards would be a better name. But what does generate mean here? (I'm not a native English speaker, but would draw_cards describe it accurately?)
string set_cards(int c){return cards[c];}
A method called set_* usually modifies something. This one doesn't. Why did you name it this way?
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
Give better names to the parameters. From reading only this declaration, I have no idea what i and max_i might mean.
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
It looks strange that the cards are stored in the Player class, since no poker player should ever have insight to all 52 cards. And why 53? Is there a joker in your game? These three fields should be moved to a class Table. This allows you to have multiple independent tables, which is nice for a big tournament.
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
Before reading the choice1 variable, you must initialize it. Since you don't do it, you invoke undefined behavior and everything that the program does after that is unpredictable.
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
Same here. The user hasn't yet entered anything, so how can you check it?
cin>>i;
Add error handling for every input by enclosing it in an if clause: if (std::cin >> i) {.
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
Don't use arrays, use a std::vector instead. This allows you to easily extend the table to have 10 players. In the end, there should not be a single 6 in your program.
player[0].card_generator();
max_i = i;//max_i is nb of players
Why do you call this variable max_i, when the comment says that max_players would be a better name?
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
What does the V in tempV mean?
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
This 17 is a magic number. It would be better to write it as 5 + 6 * 2, since that makes it much clearer.
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
The 53 is wrong here. I can only be wrong. When you select from 52 cards with equal probability, it must be % 52.
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
Captain Giraffe has answered this question in the comments. If any newbies like me face a similar problem look up what a debugger is, as errors like these are called run-time errors. Check this page for a simple explanation: http://www.cplusplus.com/forum/articles/28767/ .

Unwanted output repetition and matrix search issues

This code is an attempt to search for a target value (item) in a 5x5 matrix that I hard-coded values into. It queries the user for the value to be searched for. The problem is, when I run the code it tells me "Item found!" regardless of the user input. Also, It appears to be repeating user input. For example, when I used "87" as the user input, this is my output:
What is the value you'd like to search for? 878787Item found!
I'm fairly new to C++ so forgive me if I did something stupid. The code is as follows:
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
int target;
int flag;
int mat[5][5]= //hardcoded the matrix data
{
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20},
{21,22,23,24,25}
};
cout<<"What is the value you'd like to search for? ";
cin>>target;
for(int x=0;x<5;x++)
{
for(int y=0;y<5;y++)
{
if (mat[x][y]==target)
{
flag=1;
break;
}
else
{
//do nothing
}
}
}
if(flag == 1)
{
cout<<"Item found!";
}
else
{
cout<<"Item not found.";
}
return 0;
}
As aslg mentioned in his comment you break only your inner loop, you need to beak the outer for(int x=0;x<5;x++) loop as well. You can do this after the inner loop by stating:
if(flag==0){
break;
}
But this is not a particularly elegant solution. I suggest you let the standard library do the job.
int* end = mat[0]+25;
int* found = std::find(mat[0],end,target);
if(found!=end)
{
cout<<"Item found!";
}
else
{
cout<<"Item not found.";
}
Whats going on here: In fact the static multidimensional 5x5 array is stored as a one-dimensional array of size 25. mat[0] points to its start and mat[0] + 25 to its end. std::find(start,end,target) returns the pointer to the target if it can be found within [start,end[, else end is returned.

C++ error at the last line of code

I'm a begineer in C++ programming but I know the basics.
I recently started writing a simple game. The program chooses a random number
(1-100) and you have to guess it. There are 2 modes:
Normal - whenever you enter a number program tells you if it's bigger than the random or smaller.
hard - no clues, just pure luck.
Everything was running ok but when I added some fixes to the displayed text the program won't compile. I use CODE::BLOCKS.
Screenshot: http://scr.hu/81tw/m6cm0
I really apreciate your help.
Full code below:
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int number_normal;
int number_hard;
int guess_normal;
int guess_hard;
int tries_normal=0;
int tries_hard=0;
int mode;
int main()
{
{
cout<<"Choose your mode..."<<endl;
cout<<"Normal (Press 1) or Hard (Press 2)"<<endl;
cin>>mode;
if(mode=1)
cout<<"Normal mode chosen."<<endl;
goto normal;
if(mode=2)
cout<<"Hard mode chosen!"<<endl;
goto hard;
return 0;
}
{
hard:
cout<<"I chose a random number in a range from 1 to 100, can you guess it?"<<endl;
srand(time(NULL));
number_hard = rand()%100+1;
while(guess_hard!=number_hard)
tries_hard++;
cout<<"Enter your guess!(Try "<<tries_hard<<"): ";
cin>>guess_hard;
if(guess_hard=number_normal)
cout<<"Respect! You guessed it in "<<tries_hard<<" tries!"<<endl;
}
{
normal:
cout<<"I chose a random number from 1 to 100. I will give you some clues! Try to guess it."<<endl;
srand(time(NULL));
number_normal = rand()%100+1;
while(guess_normal!=number_normal)
tries_normal++;
cout<<"Enter your guess!(Try "<<tries_normal<<"): ";
cin>>guess_normal;
if(guess_normal==number_normal)
cout<<"Congrats! You're lucky. (Won in "<<tries_normal<<" tries!)"<<endl;
if(guess_normal<number_normal)
cout<<"Too low."<<endl;
else if(guess_normal>number_normal)
cout<<"That's too much!"<<endl;
system("pause");
return 0;
}
The code that works is here
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int number_normal;
int number_hard;
int guess_normal;
int guess_hard;
int tries_normal=0;
int tries_hard=0;
int mode;
int main()
{
{
cout<<"Choose your mode..."<<endl;
cout<<"Normal (Press 1) or Hard (Press 2)"<<endl;
cin>>mode;
if(mode=1)
cout<<"Normal mode chosen."<<endl;
goto normal;
if(mode=2)
cout<<"Hard mode chosen!"<<endl;
goto hard;
return 0;
}
{
hard:
cout<<"I chose a random number in a range from 1 to 100, can you guess it?"<<endl;
srand(time(NULL));
number_hard = rand()%100+1;
while(guess_hard!=number_hard)
{
tries_hard++;
cout<<"Enter your guess!(Try "<<tries_hard<<"): ";
cin>>guess_hard;
if(guess_hard==number_normal)
cout<<"Respect! You guessed it in "<<tries_hard<<" tries!"<<endl;
}
}
{
normal:
cout<<"I chose a random number from 1 to 100. I will give you some clues! Try to guess it."<<endl;
srand(time(NULL));
number_normal = rand()%100+1;
while(guess_normal!=number_normal)
{
tries_normal++;
cout<<"Enter your guess!(Try "<<tries_normal<<"): ";
cin>>guess_normal;
if(guess_normal==number_normal)
cout<<"Congrats! You're lucky. (Won in "<<tries_normal<<" tries!)"<<endl;
if(guess_normal<number_normal)
cout<<"Too low."<<endl;
else if(guess_normal>number_normal)
cout<<"That's too much!"<<endl;
//system("pause");
}
}
return 0;
}
Well, you didn't used braces across your while loops, and as #cowls suggested, there was a closing brace missing after main. Everything else was fine. Also you used a = for comparison between to variables, instead of ==, = is a assignment operator, while == is used for comparison.
You are missing a close brace at the end } that will close your main method.
I would also pay attention to the comments against the question addressing the other issues in your code.
Note: this could not be seen from the screenshot, showing why that was a bad format to post your code in.