Need help outputting things from different functions (C++) - 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.)

Related

How can I save a variable in my function to use it again?

I am working on something as a starter at coding, I want to get better so I'm practicicing by making a small program. Now, my aim is to attack a monster and then display its hp and then attack again and display the new HP. I've tried many different loops but each time the program doesn't save the new hp and just gives me the same hp instead of taking it away further. Any help is greatly appreciated, I've tried looking online but I can't seem to find an answer for this.
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
int hollowHP();
int blade();
int main() {
srand(time(NULL));
int damage = blade();
int health = hollowHP();
int newHP = health - damage;
int newDamage = rand() % 11;
int remainingHP = newHP - newDamage;
string answer;
cout << "A hollow stands before you with " << hollowHP() << " amount of HP!"
<< endl;
cout << "fight or flight?" << endl;
cin >> answer;
if (answer == "fight") { cout << "Your blade did " << damage << " amount of
damage!" << endl << "the hollow now has: " << newHP << " HP" << endl; }
if (answer == "flight") { cout << "You have failed to protect those in need,
others will come to take the job off your hands.. coward." << endl; }
do {
cout << "continue fighting?" << endl;
cin >> answer;
if (answer == "yes") {
cout << "Your next attack did " << newDamage << " amount of damage!"
<< endl << "the hollow now has: " << newHP - newDamage << " HP" << endl;
} if (answer == "no") {
cout << "you tried i guess" << endl;
}
} while (health != 0);
cout << "Hurray! You've defeated the hollow and saved many innocent lives!
You're a true hero." << endl;
system("pause");
return 0;
}
int hollowHP() {
int hollow = 50;
return hollow;
}
int blade() {
int slash = 1;
int spiritEnergy = rand() % 11;
int totalSlash;
totalSlash = slash + spiritEnergy;
return totalSlash;
}
Onk_r has the right answer: static variables within the body ({}) of a function 'stick around'. Specifically, the expression which initializes the value of a static variable within a function body is executed only once, so the next time you call that function whatever value it had last will remain.
However, that won't solve your problem: your code is written with the assumption that every time you use a variable the expression that initialized it will be executed. When you use the name damage, for instance, the program will not execute the function blade(). Damage will only receive the value returned by blade() the one time, when you declared the variable damage:
int damage = blade();
That line only ever executes once in the whole lifetime of the program. Similarly, newHP will only ever have the value of health - damage at the time it was initialized. When damage was initialized, if blade() returned 8, then newHP will always have the value 42;
C++ doesn't store expressions; it evaluates them. That is what the type system ensures: the type stored in damage is int, it cannot have the type "expression" (not a thing in C++, though there are all kinds of ways implementing something like that). When you assign a variable, the value of the expression is stored, not how it was calculated. Every time the user attacks you really need to do something like:
newHP = health - blade();
/* Output message */
health = newHP;
Like Norhther said.
You are relying on functions to store state here, too, which isn't bad but in C++ you can, and generally should, do better. Specifically, class Hollow or the easier struct Hollow would be better than some variables floating around inside main().
for saving value in function in C++ or C for future use you can simply declare it as static and when leaves I mean return from function set that variable to that value which you want to save.

C++ Guessing Game Error

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

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

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

Syntax Query, calling modules in Visual C++

I have tried to adapt my knowledge of modularity to Visual C++ however, upon what seems to be an endless search scouring for syntax, I simply can't get this right. Basically in this code, the menu is called first, once the user enters their choice (only coded option 1 thus far) to return that value to the main, which then steps into the if statement and calls fahrenheit. I am requesting the syntax for passing by reference, I know C#'s syntax for this, but not Visual C++
Here's the code.
// Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void Celsius()
{
}
void fahrenheit()
{
cout << "Success!" << endl; //....Outputs this just to see if the module is being called properly.
}
int menu(int Mystring) //....I was testing this syntax to pass the variable.
{
cout << "What would you like to do : " << endl;
cout << "1) Fanreheit to Celsius" << endl;
cout << "2) Celsius to Fahrenheit" << endl;
cout << "Choice : " ;
cin >> Mystring;
return Mystring;
}
int main()
{
int celsius = 0;
int fahrenheit = 0;
int Mystring = 0;
menu(Mystring); //....Testing this syntax to pass Mystring to menu.
if (Mystring == 1) //....I was hoping the menu would return Mystring as value = 1.
{
fahrenheit(); //.......I want this to call fahrenheit module if Mystring = 1
}
}
The "things" you're talking about aren't called modules, but functions. That's a pretty big difference and I think you should know it, since you won't understand nearly any article without that knowledge.
That being cleared, the problem in your code is, that you pass the variable by value (int menu(int Mystring)), while - in order to change it inside the function - you need to pass it by reference or pointer:
int menu(int &Mystring)
There are plenty of articles about functions in C++. You should check them out probably.