C++ Guessing Game Error - c++

I do not know how to declare "random" in the parentheses for "int main()," and need help. (I am a beginner in C++)
Please take a look at my code, try it out, and please notify me with an answer when you think you know how to solve this problem. It'd mean a lot to me. Thanks! Meanwhile, I will keep trying to solve the problem myself as well.
Note: I am using Code::Blocks if you want to be specific.
The error is on Line 7/9 of my code.
Here is my updated code below:
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
int rn = random() % 21; // generates a random int from 0 to 20
// First output asking the user to guess the number
cout << "Please guess my number :" << endl;
int u;
cin >> u;
while (u != rn) // Calculates the answer that you give
{
// If the user's number is greater than the random number
// the program will let you know it's too large
if (u > rn)
{
cout << "You guessed too big!" << endl;
}
// On the other hand, if the user guesses to small
// the program will tell them that it's too small
else if (u < rn)
{
cout << "You guessed too small!" << endl;
}
// If the user does not get the right number, the program
// will tell the user to guess again
cout << "Please guess again :" << endl;
cin >> u;
}
// If the user guesses the number correctly, the program
// will say that they got it right, and end the program
cout << "You guessed it right!" << endl;
getch();
}
Here's the updated compiler error:
||=== Build: Debug in Guess The Number (compiler: GNU GCC Compiler) ===|
C:\Users\Minecraftship\Documents\CPP Programs From Book\Guess The Number\main.cpp||In function 'int main()':|
C:\Users\Minecraftship\Documents\CPP Programs From Book\Guess The Number\main.cpp|12|
error: 'randomize' was not declared in this scope|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Remove the semicolon near main, the compiler is telling you exactly what the issue is:
int main ();
Should be
int main ()
Your code will also not compile even after fixing this because you have not declared the std namespace. You can put this line at the top for now using namespace std; but it is bad practice. You should declare it manually using the scope resolution operator.
And a number of other issues as already mentioned in the comments above, make sure to read the compiler output thoroughly because it tells you what line is causing the issue.
Your code should look like:
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
int rn = random() % 21; // generates a random int from 0 to 20
// First output asking the user to guess the number
cout << "Please guess my number :" << endl;
int u;
cin >> u;
while (u != rn) // Calculates the answer that you give
{
// If the user's number is greater than the random number
// the program will let you know it's too large
if (u > rn)
{
cout << "You guessed too big!" << endl;
}
// On the other hand, if the user guesses to small
// the program will tell them that it's too small
else if (u < rn)
{
cout << "You guessed too small!" << endl;
}
// If the user does not get the right number, the program
// will tell the user to guess again
cout << "Please guess again :" << endl;
cin >> u;
}
// If the user guesses the number correctly, the program
// will say that they got it right, and end the program
cout << "You guessed it right!" << endl;
getch();
}

Someone else got to it. There are no semicolons after signatures to methods like main().
One other thing not mentioned, I'm guessing you want
while (u != rn)
Also, be careful of the difference in "=" and "==".
BTW -- Welcome to C++!!!

a little more portable version (doesn't use conio.h) which lets the computer play against himself:
#include <iostream>
#include <cstdlib>
#include <ctime>
int get_random_in_range(int min, int max)
{
return std::rand() % (max - min) + min;
}
// returns 0 if user guessed right, negative value if user
// guessed too small, positive if user guessed too big
int check_user_guess(int guess, int my_secret)
{
return guess - my_secret;
}
int main ()
{
int my_guess = get_random_in_range(1, 10);
std::cout << "I think of " << my_guess << std::endl;
std::cout << "Please guess my number: ";
int user_guess = get_random_in_range(1, 10);
std::cout << user_guess << std::endl;
while (check_user_guess(user_guess, my_guess) != 0)
{
std::cout << "You guessed " << user_guess << std::endl;
if (check_user_guess(user_guess, my_guess) > 0)
{
std::cout << "You guessed too big!" << std::endl;
}
else if (check_user_guess(user_guess, my_guess) < 0)
{
std::cout << "You guessed too small!" << std::endl;
}
std::cout << "Please guess again: ";
user_guess = get_random_in_range(1, 10);
std::cout << user_guess << std::endl;
}
std::cout << std::endl << "You guessed it right!";
}
try it here: http://coliru.stacked-crooked.com/a/5bf0b9201ef57529

Related

Program furthering learning using Classes, private, public, constructor, functions, integers, and strings

In my c++ class, we have been tasked to keep building different aspects into this code. I am currently getting 2 errors and am stuck where I don't know what I am doing wrong. The program takes a private car or string for a name and a private integer to be input into the game checking for divisibility by 3, 5, and both 3 & 5. I am to use a get function and a put function within the class taking the input values and outputting them. I have essentially figured out the program but it will not compile and I am really unsure why. Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
using std::istream;
// declare the max size the username input can be
const int MAX = 14;
enum FIZZBUZZ { ABORT = 0, FIZZBUZZ, FIZZ, BUZZ };
class CFizzbuzz // Class definition at global scope
{
// make sure our constructor, destructor, plus member functions are
// all public and available from outside of the class.
public:
CFizzbuzz() {} // Default constructor definition
~CFizzbuzz() {} // Default destructor definition
// function members that are public
// get the user's name and their value from the console and
// store those results into the member variables.
void getFizzbuzz()
{
cout << "Please enter your name: " << endl;
cin >> m_myName;
cout << "Please enter your number for the FizzBuzz game: " << endl;
cin >> m_myNum;
}
// return the user's number type entered
int putFizzBuzz()
{
return m_myNum;
}
char* getName()
{
return m_myName;
}
// logic to check to see if the user's number is 0, fizz, buzz, or fizzbuz
int getRecord(int num)
{
if (num == 0)
{
return ABORT;
}
else if (num % 5 == 0 && num % 3 == 0) // fizzbuzz number
{
return FIZZBUZZ;
}
else if (num % 5 == 0) // buzz number
{
return BUZZ;
}
else if (num % 3 == 0) // fizz number
{
return FIZZ;
}
else
return num;
}
// private data members only available inside the class
private:
int m_myNum;
char m_myName[MAX];
};
int main()
{
CFizzbuzz myClass;
cout << "Welcome to my Fizzbuzz game, you are to guess the location of a "
<< "number which if is divisible by 5 and 3 you will win with "
<< "the output of Fizzbuzz. " << endl;
cout << "Please enter an integer value between 0 and 3 "
<< "representing the row location of the number for the game, "
<< "then press the Enter key: " << endl;
for (;;)
{
myClass.getFizzbuzz();
int num = myClass.putFizzBuzz();
switch (myClass.getRecord(num))
{
case ABORT:
cout << myClass.getName() << "\nThank you for playing\n";
system("PAUSE");
return 0; // exit program
case FIZZ:
cout << "Sorry, " << myClass.getName() << ", number is a Fizz, please try again.\n";
break;
case BUZZ:
cout << "Sorry, " << myClass.getName() << ", number is a Buzz, please try again.\n";
break;
case FIZZBUZZ:
cout << "You win you got FizzBuzz!!!" << endl;
break;
default:
cout << "Sorry, " << myClass.getName() << ", number is a not a Fizz, Buzz, or Fizzbuzz\nPlease try again.\n";
break;
}
}
}
These are errors I'm getting:
LNK2019, LNK1120
Based on the errors you mentioned in comments (Unresolved external symbol _WinMain#16) I'd say that you created a Win32 project (a GUI project) in Visual Studio but your code is meant to be a console application.
You need to change the type of your project from Win32 application to Console application by either re-recreating it or changing the Subsystem from Windows to Console in project settings. See the following link for more information on the latter:
https://msdn.microsoft.com/en-us/library/fcc1zstk.aspx
I would be suspicious of the else return num. What happens when you enter 1 or 2? Clearly the modulus doesn't provide a fizz or buzz but based on your enum values the function getRecord() returns that it does. I would have a NONE enum value set to -1 to indicate that it is neither a fizz or buzz.
The thing to remember about an enum value is that it resolves to an actual number when compiled. So when you input 1, and the modulus doesn't prove a fizz, buzz, or a fizzbuzz AND you return 1, the switch case statement will resolve to fizzbuzz even though this is not the case (pun intended).
As far as you commenting that it's not working as expected, please input more details.

receiving a debug error when attempting to run program

I am receiving the following debug error when attempting to run the first part of my program:
Debug Error!
Program:
...\user\desktop\PunchLineProgram\Debug\PunchLineProgram.exe
Module:
...\user\desktop\PunchLineProgram\Debug\PunchLineProgram.exe
File:
Run-Time Check Failure #3 - T
(Press Retry to debug the application)
I am attempting to have the user select whether they want to hear a joke, running and if\else statement that will output a message to the user, based on their response. If I comment out these statements, I do not receive the error when attempting to run the program. I know I'm probably missing something simple, as I am a novice. Here is the code that I have so far:
/*Include Section*/
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <cctype>
/*Namespace Section*/
using namespace std;
/*Function Prototypes Section*/
void displayAllLines(ifstream &infile);
void displayLastLine(ifstream &infile);
/*Main section: this is the entry point of the program, which controls the flow of execution*/
int main()
{
string file1;
string file2;
ifstream joke;
ifstream punchline;
int decision;
char y;
char n;
cout << "*******************************************************************************" << endl;
cout << setw(48) << "Punchline Program" << endl;
cout << "*******************************************************************************" << endl;
cout << endl;
cout << "Welcome to the Punchline Program!" << endl;
cout << "Are you ready to hear a joke? (y or n): ";
cin >> decision;
if (decision == y)
{
cout << "Great! Let's get started!" << endl;
}
else if (decision == n)
{
cout << "Ah, no sense of humor, I see. Time to make like a tree and leaf (queue rimshot)!" << endl;
}
system("PAUSE");
}
Any help would be greatly appreciated!
When comparing to char you should use '':
char answer
if (answer == 'y') { *//this only checks for LOWER case y*
cout << "You selected Yes" << endl;
}
when comparing to a string use ""
int/float/double... you can just use the variable.
Besides that, your decision variable as int when it should be char, and you don't need char y nor n. (you yourself never even used it in that code)
I'd suggest looking up c++ tutorials, most show and explain the different between char/string, ' and ".

Reading into an Array Multiple Times

I'm having a little trouble with my code. It's pretty much supposed to open two files, and compare the first twenty line of the file "StudentAnswers.txt" [inputted as a char into a char array] against a char value in (each line of another file) "CorrectAnswers.txt" in another array at the same position (index). It's like a linear search, but the same position in the arrays. Then a report should be displayed, detailing which question the student missed, the given answer, the correct answer, and if the student passed (got >= 70%) or not, like the following:
Report for Student X:
2 (A/D), 3 (C/D), 5(D/A)
This student passed the exam!
Then it should clear the SAArray, and feed the next twenty lines from StudentAnswers.txt, and start the process all over again. I guess the program has to determine the number of students from (lines of 'StudentAnswers.txt' file / 20).
I'm having trouble displaying the report, and having the array clear itself after the program. I'm guessing this can be done with a while loop and an accumulator for the number of students (to be determined by above equation).
Also, Visual Studio seems to go to "Missed __ questions for a total of ___ %", and then keep looping -858993460.
Any help would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
#include <array>
#include <algorithm>
using namespace std;
void GradeReturn(char[], char[], int, int, int);
string PassFail(float);
int main()
{
ifstream SA("StudentAnswers.txt");
ifstream CA("CorrectAnswers.txt");char CAArray[20];
char SAArray[20];
// char SA2Array[20];
bool isCorrect;
int correct;
int incorrect;
int counter;
correct = 0;incorrect = 0;
counter = 0;
cout << endl;
if (!SA.fail())
{
cout << "'StudentAnswers.txt' file opened successfully." << endl;
cout << "'CorrectAnswers.txt' file opened successfully." << endl << endl;
int a = 0;
int b = 0;
while (a < 20)
{
CA >> CAArray[a];
a++;
} // while loop to feed char into the array
while (b < 20)
{
SA >> SAArray[b];
b++;
}
} // while loop to feed char into array
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter);
return 0;
}
void GradeReturn(char CAArray[], char SAArray[], int correct, int incorrect, int counter)
{
float percent;
float hundred;
int student;
int catcher[20];
int writeCatcher; int starter;
int catcher_size;
student = 0;
writeCatcher = 0;
catcher_size = ((sizeof catcher) / 4);
while (counter < 20)
{
if ((CAArray[counter]) == (SAArray[counter]))
{
correct++;
cout << "Good job!" << endl;
} // correct handling
else
{
incorrect++;
cout << "You got question " << counter << " wrong." << endl;
counter >> catcher[writeCatcher];
writeCatcher++;
} // incorrect handling
counter++;
} // while loop to determine if a student got a question right or wrong
static_cast <float> (incorrect); // float conversion
cout << endl; // for cleanliness
percent = ((static_cast <float> (correct)) / 20); // percentage
hundred = percent * 100;
PassFail(percent);
if (PassFail(percent) == "pass")
{
student++;
cout << "Report for Student " << student << ":" << endl;
cout << "-----------------------------" << endl;
cout << "Missed " << incorrect << " questions out of 20 for ";
cout << hundred << " % correct." << endl << endl;
starter = 0;
while (starter < (sizeof catcher)
{
if(1=1)
{
catcher_size
}
else
{
cout << "";
starter++;
}
}
}
else if (PassFail(percent) == "fail")
{
student++;
cout << "Missed " << incorrect << " questions out of 20 for ";
cout << hundred << " % correct." << endl << endl;
while (starter < catcher_size)
{
if ((catcher[starter]) == -858993460)
{
starter++;
}
else
{
cout << "";
starter++;
}
}
}
return;
}
string PassFail(float percent)
{
if (percent >= 0.70) // if <pass>
{
return "pass";
}
else // if <fail>
{
return "fail";
}
cout << endl;
}
To get a loop you should keep streams open instead of closing them after reading 20 lines.
As pseudo code that would be:
a = 0;
while(streams_not_empty)
{
CA >> CAArray[a];
SA >> SAArray[a];
++a;
if (a == 20)
{
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter);
a = 0; // Reset a
}
}
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
You would also need to pass correct, incorrect, counter by reference so that the GradeReturn can change their value and their by do the accumulation.
Like:
void GradeReturn(char CAArray[], char SAArray[], int& correct, int& incorrect, int& counter)
Further you shouldn't rely on being able to read exactly Nx20 lines from the files every time. A file could have, e.g. 108 (5x20 + 8) lines, so you code should be able to handle the with only 8 lines. In other words, don't hard code 20 in your function like while (counter < 20). Instead pass the number of lines to be handled and do while (counter < number_to_handle).
Something like this as pseudo code:
a = 0;
while(streams_not_empty)
{
CA >> CAArray[a];
SA >> SAArray[a];
++a;
if (a == 20)
{
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter, a);
// ^
a = 0; // Reset a
}
}
if (a != 0)
{
// Process the rest
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter, a);
}
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
One problem you have is you're trying to compare C-style strings with the == operator. This will compare them essentially as if they were pointers to char, i.e. compare whether they point at the same location in memory, not compare the contents of the string. I urge you to look up array-decay and c-string variables to understand more.
Specifically, if (PassFail(percent) == "pass") isn't going to do what you want it to. strcomp doc, strncmp doc using std::string variables instead of c-style strings would all work, but it would be better simply to compare percent to a value, i.e. if(percent >= 0.70 directly instead of calling PassFail and comparing a string.
There are many other issues here also, you at one point call PassFail but do nothing with the return value. The only side affect of PassFail is cout << endl, if that's what you intend, it's a poor decision and hard to read way to put a newline on the console.
Try asking your compiler for more warnings, that's often helpful in finding these types of issues. -Wall -Wextra work for gcc, you may have to read your compiler manual...

Need help outputting things from different functions (C++)

I am fairly new to C++ and coding in general. I am trying to make just a basic little multiple choice type game for practice but I have run into a conundrum.
The program isn't outputting what I want it too. Here is the code:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
void sword(int damage);
void fists(int damage);
static int enemyHealth = 250;
int main() {
srand(time(0));
string SOF; //Abreveation for "Sword Or Fists"
cout << "You will be fighting a mean bad guy. Are you using a sword, or your fists?\n";
while (SOF != "sword" && SOF != "fists"){
cout << "Please enter your choice of either 'sword' or 'fists': ";
cin >> SOF;
}
cout << "Okay! Time to fight! \n";
if (SOF == "fists") {
void fists();
}
else if (SOF == "sword") {
void sword();
}
else{ (NULL); }
cout << "Congratulations! You have vanquished that foul beast!\n";
system("pause");
}
//This is for when the user chooses 'sword'
void sword(int damage = rand() % 100 + 50) {
while (enemyHealth > 0){
cout << "You deal " << damage << " damage with your sharp sword. \n";
enemyHealth -= damage;
}
}
//This is for when the user chooses 'fists'
void fists(int damage = rand() % 10 + 4) {
while (enemyHealth > 0){
cout << "You deal " << damage << " damage with your womanly fists. \n";
enemyHealth -= damage;
}
}
The first part works fine, but when I enter my choice of either "fists" or "sword" the output is:
Okay! Time to fight!
Congratulations! You have vanquished that foul beast!
But I want it to output the damage being done with either fists or sword.
If I could get some help with that, it would be amazing. Thanks!
void fists(); is a declaration, not a call, change to fists(); and sword();
Other things to look at:
Default parameters are declared in function declaration before main (or just move whole functions there)
Default parameters in c++ are evaluated once, so all 'hits' will be the same in your code
Local variable names are usually not named in uppercase, SOF looks loke it is a #defined constant or such.
To call the function, don't write void fists();, just
fists();
(What you have is a declaration, which has no useful effect here, rather than a call.)

c++ using random numbers to decide the next encounter

EDITED for full code
I am trying to make a text based rpg game because im really bored and want to put my c++ "skills" at test xd.
But i am having a problem with the functions srand and rand, the function to generate random numbers.
What i want do achieve, is to let the RNG decide the next action of the game. I.e :
#include <iostream>
#include <windows.h>
#include <string>
#include "conio.h"
#include <time.h>
using namespace std;
void GetRandom();
int main()
{
int x;
string name;
srand(time(NULL));
cout << "welcome to adventurers world!" << endl;
cout << "you wake up on an island far far away and you don't know where you are" << endl;
Sleep(2000);
cout << "Please enter the name of your adventurer" << endl;
getline(cin, name);
cout << "hello " << name << endl;
Sleep(1000);
cout << "where would you like to go, " << name << " ?" << endl;
Sleep(1000);
cout << "1. waddle around the beach\n2. go to the cave straight ahead\n3. go into the forest" << endl;
cin >> x;
if(x==1)
{
cout << "you waddle abit around on the beach, and you suddenly " << random;
}
_getch();
}
void random()
{
srand(time(NULL));
int randnumber = rand() % 2 + 1;
randnumber = randnumber;
if(randnumber == 1)
{
cout << "you encounter a mudcrab" << endl;
}
else if (randnumber == 2)
{
cout << "you find a stick" << endl;
}
}
What i want do achieve here is, if the random number generated is 1 do (randnumber == 1) and if it is 2, do (randnumber == 2)
but instead it just gives me a hexidecimal as output.
is my code properly written? am i using the right expression for srand, calculation w/e.
And is this even possible to do? or do i have to write it out manually what will happen next, which wont make it as much a dynamic game.
thanks for your help and time
At the moment, you're not calling the function random, you're displaying its address. Try this:
if(x==1)
{
cout << "you waddle abit around on the beach, and you suddenly ";
random();
}
Don't seed the random generator with the time each time you need a random number. Unless the usage is a long time between (more than a second), that will set the seed to the same value.
Don't name your function random(). That will make the random() function inaccessible. It probably should be choose_random_object() or something like that.
Seed the random number generator once when the program begins, and only reseed it if you need to repeat the random numbers (unlikely in a situation such as this).
Calling a function should return a value which is useful—which yours is not. Call a procedure (a function which does not return a value) for its side-effects, such as printing out a word.
Here's what your code should look like. The comments give an explanation of the changes.
srand(time(NULL)); // srand() needs only to be called once in the beginning.
if(x == 1)
{
cout << "you waddle abit around on the beach, and you suddenly ";
GetRandom(); // call the function to output what you need.
}
void GetRandom() // change the name of the function.
{
int randnumber = rand() % 2 + 1;
// no need for: randnumber = randnumber;
if(randnumber == 1)
{
cout << "you encounter a mudcrab" << endl;
}
else // no need for else if since the random # cannot be anything else but 2
{
cout << "you find a stick" << endl;
}
}