Newbie C++ issue involving while loops and OR statements - c++

I am having an issue learning C++ basics involving the while loop. When
I run my program it works well, until I get to the while loop involving an OR (||) statement. while (totalhumanHP > 0 || totalskeletonHP > 0) should continue until one hits zero then stop correct?
It is only keeping tabs on totalhumanHP and letting skeletonHP dip into the negatives without stopping. I am not sure how or why the OR statement isnt functioning in the while loop.
#include <iostream>
#include <string>
#include <random>
#include <ctime>
using namespace std;
int main()
{
cout << "-----SKELETMANS V HOOMINS-----\n";
int skeletonHP = 90;
int humanHP = 100;
int skeletonDMG = 1;
int humanDMG = 1;
int totalskeleton = 1; //Inputted Skele's
int totalhuman = 1; //Inputted hoomins
int totalskeletonHP; //Overall Skele HP
int totalhumanHP; //Overall Hoomin HP
string battlecry;
string battlecryenter;
default_random_engine generator(time(0));
uniform_int_distribution<int> skeletonrng(1, 22);
uniform_int_distribution<int> humanrng(1, 20);
cout << "How Many Skeletmans: ";
cin >> totalskeleton;
cout << "How Many Houmints: ";
cin >> totalhuman;
totalskeletonHP = totalskeleton * skeletonHP;
totalhumanHP = totalhuman * humanHP;
cout << "Overall Skeleton HP= " << totalskeletonHP << endl;
cout << "Overall Hoomint HP= " << totalhumanHP << endl;
cout << endl;
cout << "What is your battlecry?\n (You can use this to start the battle)";
cout << endl;
cin >> battlecry;
battlecry == battlecryenter;
cout << "Use Your Battlecry To Start The Fight!!!\n\n\n\n\n";
cout << "BattleCry: ";
cin >> battlecryenter;
if (battlecryenter == battlecry)
{
cout << "THE FIGHT HAS COMMENCED!!!\n\n\n\n";
}
else{
cout << "You 4got alreedy? UR DOMB MING\n\n";
cout << "ACTUAL BattleCry: ";
cin >> battlecryenter;
if (battlecryenter == battlecry)
{
cout << "THE FIGHT HAS COMMENCED!!!\n\n\n\n";
}
}
int endskeleton = 0;
int endhuman = 0;
while (totalhumanHP > 0 || totalskeleton > 0)
{
skeletonDMG = skeletonrng(generator);
humanDMG = humanrng(generator);
totalhumanHP = totalhumanHP - skeletonDMG;
totalskeletonHP = totalskeletonHP - humanDMG;
cout << "END SKELETON: " << totalskeletonHP << endl;
cout << "END HOOMING: " << totalhumanHP << endl;
}
cout << "Skeleton Ramaining Health: " << totalskeletonHP << endl;
cout << "Human Remaining Health: " << totalhumanHP << endl;
system("PAUSE");
return 0;
}

That's because you used OR, so even if skeletonHP is negative, that condition is still true since totalhumanHP is greater than 0.
Just change it with:
while (totalhumanHP > 0 && skeletonHP > 0)
When either one reaches 0, the loop will stop.

Related

Error: expected primary-expression before ']' token. Need assitance with function definition and calling

This is my first semester of computer science, and I need help with my first project. So far, it's still a mess, and I am mainly doing test cases to ensure basic things like my functions work.
The goal of the project is to ask the user how many robots they want to make, name them, then they can use the robot's name (their unique identifier) to move the robots along an X-Y axis, which is really just the program adding or subtracting to a .Xvalue or .Yvalue.
My MenuFunction works, but I am having trouble with the MoveFunction. Basically, I want the MoveFunction to ask the user which robot they want to use, go through the RobotArray, and print the Robot's name once found.
Again, this is just a test case so I can better understand the coding. Right now, I am getting two errors:
main.cpp:42:33: error: expected primary-expression before ‘]’ token
42 | string MoveFunction(RobotArray[], robotName, NumberOfRobots);
main.cpp:62:16: error: no match for call to ‘(std::string {aka std::__cxx11::basic_string}) ()’
62 | MoveFunction();
I don't know what to do for the first error, but I think the latter is due to my not having any objects in the function call, but I wouldn't know what to put in there anyway.
My complete code is below:
#include <iostream>
using namespace std;
struct userRobot
{
string name;
int Xvalue = 0;
int Yvalue = 0;
};
void MenuFunction()
{
cout << "Welcome to MultiRobo Guider." << endl;
cout << "Please select:" << endl;
cout << "m - move" << endl << "d - distance" << endl << "q - quit" << endl << endl;
}
int main()
{
int NumberOfRobots;
string robotName;
cout << "Enter the number of robots" << endl;
cin >> NumberOfRobots;
cout << endl << "Enter their name(s)" << endl;
userRobot RobotArray[NumberOfRobots];
for (int i = 0; i < NumberOfRobots; i++)
{
cin >> robotName;
RobotArray[i].name = robotName;
}
cout << endl;
for (int j = 0; j < NumberOfRobots; j++)
{
cout << RobotArray[j].name << "'s position is ";
cout << "(" << RobotArray[j].Xvalue << "," << RobotArray[j].Yvalue << ")" << endl << endl;
}
string MoveFunction(RobotArray[], robotName, NumberOfRobots);
{
cin >> robotName;
for (int k = 0; k < NumberOfRobots; k++)
{
if (robotName == RobotArray[k].name)
{
cout << RobotArray[k].name;
}
}
}
MenuFunction();
char input;
cin >> input;
if (input == 'm')
{
cout << "Which robot would you like to move?";
MoveFunction();
}
else if (input == 'd')
{
cout << "distance";
}
else if (input == 'q')
{
cout << "quit";
}
}
First off, userRobot RobotArray[NumberOfRobots]; is a variable-length array, which is a non-standard extension supported by only a few compilers. To create an array whose size is not known until runtime, you should use new[] instead, or better std::vector.
That said, your main issue is that you are trying to define your MoveFunction() function inside of your main() function, which is not allowed. But, even if it were, you are not declaring it correctly. It has an erroneous ; on it. And RobotArray, robotName, and NumberOfRobots are not types, but variables. Like a variable, a function parameter always starts with a type. There are no untyped parameters/variables in C++.
You need to either:
move MoveFunction() outside of main(), and fix its declaration to use proper types, eg:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct userRobot
{
string name;
int Xvalue = 0;
int Yvalue = 0;
};
void MenuFunction()
{
cout << "Welcome to MultiRobo Guider." << endl;
cout << "Please select:" << endl;
cout << "m - move" << endl << "d - distance" << endl << "q - quit" << endl << endl;
}
void MoveFunction(userRobot RobotArray[], int NumberOfRobots)
{
cout << "Which robot would you like to move?";
string robotName;
cin >> robotName;
for (int k = 0; k < NumberOfRobots; k++)
{
if (robotName == RobotArray[k].name)
{
cout << RobotArray[k].name << endl;
return;
}
}
cout "Robot not found" << endl;
}
int main()
{
cout << "Enter the number of robots" << endl;
int NumberOfRobots;
cin >> NumberOfRobots;
vector<userRobot> RobotArray(NumberOfRobots);
cout << endl << "Enter their name(s)" << endl;
for (int i = 0; i < NumberOfRobots; i++)
{
cin >> RobotArray[i].name;
}
cout << endl;
for (int j = 0; j < NumberOfRobots; j++)
{
cout << RobotArray[j].name << "'s position is ";
cout << "(" << RobotArray[j].Xvalue << "," << RobotArray[j].Yvalue << ")" << endl << endl;
}
MenuFunction();
char input;
cin >> input;
if (input == 'm')
{
MoveFunction(RobotArray.data(), NumberOfRobots);
}
else if (input == 'd')
{
cout << "distance";
}
else if (input == 'q')
{
cout << "quit";
}
}
or change MoveFunction() into a lambda, eg:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct userRobot
{
string name;
int Xvalue = 0;
int Yvalue = 0;
};
void MenuFunction()
{
cout << "Welcome to MultiRobo Guider." << endl;
cout << "Please select:" << endl;
cout << "m - move" << endl << "d - distance" << endl << "q - quit" << endl << endl;
}
int main()
{
cout << "Enter the number of robots" << endl;
int NumberOfRobots;
cin >> NumberOfRobots;
vector<userRobot> RobotArray(NumberOfRobots);
cout << endl << "Enter their name(s)" << endl;
for (int i = 0; i < NumberOfRobots; i++)
{
cin >> RobotArray[i].name;
}
cout << endl;
for (int j = 0; j < NumberOfRobots; j++)
{
cout << RobotArray[j].name << "'s position is ";
cout << "(" << RobotArray[j].Xvalue << "," << RobotArray[j].Yvalue << ")" << endl << endl;
}
auto MoveFunction = [&]{
cout << "Which robot would you like to move?";
string robotName;
cin >> robotName;
for (int k = 0; k < NumberOfRobots; k++)
{
if (robotName == RobotArray[k].name)
{
cout << RobotArray[k].name << endl;
return;
}
}
cout "Robot not found" << endl;
};
MenuFunction();
char input;
cin >> input;
if (input == 'm')
{
MoveFunction();
}
else if (input == 'd')
{
cout << "distance";
}
else if (input == 'q')
{
cout << "quit";
}
}
You have a semi-colon at the end of MoveFunction() definition, In C++ when you define a function the name of the function does not end with a semi-colon.

Why is failed input validation returning me to the start of my program?

Really sorry if this is a dumb question. I know it must have a super easy solution but I've been staring at this for so long I can't see it. It doesn't help that I'm really new at this either.
Long story short for some reason entering an invalid input past the first time returns me back to my menu, and sometimes also asks me to enter weight immediately after instead of allowing me to enter a menu choice. It's just all around broken and I don't know why. Thanks.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
bool loopFlag = true;
bool loopFlagTwo = true;
int choice = 0;
int time = 0;
float weightPounds = 0;
float weight = 0;
const int BIKING = 8;
const int RUNNING = 10;
const int LIFTING = 3;
const float YOGA = 2.5;
int main()
{
cout << "Welcome to my Fitness Center" << endl;
do
{
cout << "\n\t____________________________________________________________" << endl;
cout << "\n\t\t\tMy Fitness Center" << endl;
cout << "\t\t\tActivity System" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\t\t\t Main Menu\n" << endl;
cout << "\t\t\t1) Stationary Bike" << endl;
cout << "\t\t\t2) Treadmill" << endl;
cout << "\t\t\t3) Weight Lifting" << endl;
cout << "\t\t\t4) Hatha Yoga" << endl;
cout << "\t\t\t5) End" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\n\nEnter the workout that you wish to track, or end to exit:" << endl;
do
{
cin >> choice;
if (cin.fail() || choice > 5 || choice < 1)
{
cout << "Invalid choice. Please choose from option 1 through 5." << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else if (choice == 5)
{
return 0;
}
else
{
loopFlag = false;
}
}
while (loopFlag);
do
{
cout << "\nPlease enter your weight in pounds: " << endl;
cin >> weightPounds;
if (cin.fail() || weightPounds <= 0)
{
cout << "Invalid weight entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
weight = weightPounds / 2.2;
cout << "\nYour weight is: \n" << fixed << setprecision(1) << weight << " kilograms." << endl;
if (choice == 1)
{
do
{
cout << "For how many minutes did you do this activity? " << endl;
cin >> time;
if (cin.fail() || time <= 0)
{
cout << "Invalid time entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
}
}
while (choice != 5);
return 0;
}
You need to set loopFlag to true before every do...while() you have, or use another flag, because after the first do...while(), loopFlag is always false.

How do i tell my app "stop running" after set amount rounds?

So i'm making a turn based dice game that's modeled after this game called "underground chinchiro" which was taken from an anime called "Kaiju". I need to set a limit to my program so that it only runs for a set number of rounds,
I'm only a beginner in coding so sorry for anything unusual you see in my code.
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
void roll_3_dice(int &dice1, int &dice2, int &dice3)
{
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
dice3 = rand() % 6 + 1;
return;
}
int main()
{
int cash = 90000;
int wager;
int r;
//dealer's die
int dealer1;
int dealer2;
int dealer3;
// your die
int mdice1;
int mdice2;
int mdice3;
for (int i = 0; i < 10; i++)
{
cout << "Wager up boy!"<< endl;
cin >> wager;
while (wager < 100 || wager > 90000)
{
cout << "Minimum wager is 100; Maximum wager is 90000 ";
cin >> wager;
}
cout << "You wagered: " << wager << endl;
cout << "You have " << cash - wager << " remaining" << endl;
cash = cash - wager;
cout << endl;
cout << "Dealer will now roll the dice" << endl;
roll_3_dice(dealer1, dealer2, dealer3);
cout << "Dealer rolled the following: " << endl;
cout << dealer1 << "-" << dealer2 << "-" << dealer3 << endl;
cout << "It's your turn to roll the dice." << endl;
cout << endl;
cout << "Press any key to roll the dice" << endl;
cin >> r;
roll_3_dice(mdice1, mdice2, mdice3);
cout << "You rolled the following: " << endl;
cout << mdice1 << "-" << mdice2 << "-" << mdice3 << endl;
system ("pause");
}
}
Take a look at for loops. For loops will allow you to run your code for a set number iteration.
e.g. iterate over some code 7 times.
int number_of_iterations = 7;
for(int i = 0; i < number_of_iterations; i++) {
// Your code that you would like to iterate over goes here.
}
EDIT:
As has been specified by the OP (in comments below), the issue is appears to be with the program not stopping to receive input from the user through each iteration of the for loop.
This could be for a number of reasons. My best guess would be that the stdin buffer is not clear and that std::cin continues to read in from the buffer. This could be solver by calling cin.clear() before reading in your input.
is time to learn how to use constants...
define one doing
const int max_round = 5;
and the do a while so long round is <= than max_round
Your problem is pretty unclear. Edit your code, find the section where problems occurring and paste that part only.
like:
while(cin>>wager)
{
if(condition fails)
{
break;
}
}

(C++) Code seems to be operating off the wrong loop...?

I've been playing around with some code in my down-time from my degree and I've nested a do{}while() loop inside another one but the problem I'm having is that the code keeps going until the last van is full, even after the number of parcels has been fulfilled...
The code's below. If someone could take a look at it and tell me what I've done wrong that'd be awesome. Bare in mind I've only really been coding in C++ for about a month so I've still got hella lot to learn..
#include <iostream>
using namespace std;
char cBeltFull;
int iVanCount, iParcelCount, iParcelLoaded;
float fHeaviestVanWeight, fParcelWeight, fCurrentPayload, fVanCapacity;
char cExit = 'N';
int main() {
iVanCount = 1;
iParcelLoaded = 1;
fHeaviestWeight = 0;
fVanCapacity = 410;
do {
//Get the number of parcels to dispatch
cout << "How many parcels need sending?" << endl;
cin >> iParcelCount;
do {
fCurrentPayload = 0;
do {
//Get parcel weight
cout << endl << endl << endl << "What is the weight the parcel " << iParcelLoaded << "?";
cin >> fParcelWeight;
//'Load' the parcel
cout << endl << endl << "Parcel loaded";
iParcelLoaded ++;
//Update the payload
fCurrentPayload = fCurrentPayload + fParcelWeight;
} while ((fCurrentPayload + fParcelWeight)) < fVanCapacity)
//Dispatch the van
cout << endl << endl << "Van dispatched.";
//Update the van count
iVanCount ++;
if (fCurrentPayload > fHeaviestVanWeight) {
//Update the heaviest weight
fHeaviestVanWeight = fCurrentPayload;
}
} while (iParcelLoaded <= iParcelCount);
cout << endl << endl << endl << "Vans dispatched: " << iVanCout;
cout << endl << endl << "Weight of heaviest van: " << fHeaviestWeight;
cout << endl << endl << endl << "Exit? Y for YES or N for NO." << endl;
cin >> cExit;
} while (cExit == 'N');
}
Change this
} while (((fCurrentPayload + fParcelWeight)) < fVanCapacity);
to this
} while (((fCurrentPayload + fParcelWeight)) < fVanCapacity
&& iParcelLoaded < iParcelCount);
That way you will load as many items the user inputs. You code contains many syntax errors.
I corrected them for you, but please be more careful next time you post.
#include <iostream>
using namespace std;
char cBeltFull;
int iVanCount, iParcelCount, iParcelLoaded;
float fHeaviestVanWeight, fParcelWeight, fCurrentPayload, fVanCapacity;
char cExit = 'N';
int main() {
iVanCount = 1;
iParcelLoaded = 1;
fHeaviestVanWeight = 0;
fVanCapacity = 410;
do {
//Get the number of parcels to dispatch
cout << "How many parcels need sending?" << endl;
cin >> iParcelCount;
do {
fCurrentPayload = 0;
do {
//Get parcel weight
cout << endl << endl << endl << "What is the weight the parcel " << iParcelLoaded << "?";
cin >> fParcelWeight;
//'Load' the parcel
cout << endl << endl << "Parcel loaded";
iParcelLoaded ++;
//Update the payload
fCurrentPayload = fCurrentPayload + fParcelWeight;
} while (((fCurrentPayload + fParcelWeight)) < fVanCapacity && iParcelLoaded < iParcelCount);
//Dispatch the van
cout << endl << endl << "Van dispatched.";
//Update the van count
iVanCount ++;
if (fCurrentPayload > fHeaviestVanWeight) {
//Update the heaviest weight
fHeaviestVanWeight = fCurrentPayload;
}
} while (iParcelLoaded <= iParcelCount);
cout << endl << endl << endl << "Vans dispatched: " << iVanCount;
cout << endl << endl << "Weight of heaviest van: " << fHeaviestVanWeight;
cout << endl << endl << endl << "Exit? Y for YES or N for NO." << endl;
cin >> cExit;
} while (cExit == 'N');
}

Random Guessing Game in C++

My assignment is to create a guessing game where the computer guesses my number and one where I guess the computer's number. I have my code written out but It's incomplete. I want to create a menu so the user can choose which game he wants to play, and also i am having trouble joining the two programs into one so they both will run. Can someone please assist me. The first game works fine but from there I really don't know what I'm doing.
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
const int min = 1;
const int max = 100;
int num = 2 && 3 && 4;
int prevMin = 0;
int prevMax = 0;
int tries = 0;
int guess = 0;
int userNum = 0;
int userGuess = 0;
int systemNum = 0;
int systemGuess = 0;
cout << "Welcome to the Guessing Game!" << endl;
cout << "Enter a 2 to play Game 1 or a 3 to play Game 2. Or enter 4 to quit." << endl;
cin >> num;
if (num == 2)
{
cout << "Welcome to Game 1!" << endl;
cout << "User, enter a random number between " << min << " and " << max << " : "; cin >> userNum;
}
srand(time(0));
systemGuess = rand() % 100 + 1;
do
{
cout << "System, guess the user's number between " << min << " and " << max << ": " << systemGuess << endl;
cin.get();
++tries;
if (systemGuess > max || systemGuess<min)
{
cout << "I said guess a number between " << min << " and " << max << " stupid." << endl;
}
if (systemGuess > userNum)
{
cout << "Too high. Guess lower." << endl;
prevMax = systemGuess;
systemGuess = rand() % (prevMax - prevMin) + prevMin;
if (systemGuess == prevMin)
systemGuess++;
}
else if (systemGuess < userNum)
{
cout << "Too low. Guess higher." << endl;
prevMin = systemGuess;
systemGuess = rand() % (prevMax - prevMin) + prevMin;
if (systemGuess == prevMin)
systemGuess++;
}
} while (systemGuess != userNum);
cout << systemGuess << endl;
cout << " I guessed it right! It took me " << tries << " guess(es). " << endl;
srand(time(0));
systemNum = rand()% 100 + 1;
//Beginning of second game
do
{
if (num == 3)
{
cout << "Welcome to Game 2!" << endl;
cout << "User, try to guess the computer's number that's between " << min << " and " << max << " . " << endl;
}
cout << "Enter your guess." << endl;
cin >> userGuess;
tries++;
if (userGuess > systemNum)
{
cout << "Too high. Guess lower." << endl;
cin >> userGuess;
}
else if (userGuess < systemNum)
{
cout << "Too low. Guess higher." << endl;
cin >> userGuess;
}
else
{
cout << "Correct! It took you long enough! Lol... " << endl;
cin >> userGuess;
}
while (userGuess != systemNum);
}
system("pause");
return 0;
}
Make the two games two distinct functions (each with its own local variables), create a third one that is a loop that prompts for the games (and break when "quit" is selected), and call the corresponding function, then call the third one from main.
You can use if...else :
cout << "Welcome to the Guessing Game!" << endl;
cout << "Enter a 2 to play Game 1 or a 3 to play Game 2. Or enter 4 to quit." << endl;
cin >> num;
if (num == 2)
{//game1
}
else if(num==3)
{//game2
}
else if(num==4)
{return 0;
}else
{
cout<<"Invalid choice!";
system("pause");
return 1;
}
//print highscores
system("pause");
return 0;
Your whole code:
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
const int min = 1;
const int max = 100;
int num = 2 && 3 && 4;
int prevMin = 0;
int prevMax = 0;
int tries = 0;
int guess = 0;
int userNum = 0;
int userGuess = 0;
int systemNum = 0;
int systemGuess = 0;
srand(time(0));
cout << "Welcome to the Guessing Game!" << endl;
cout << "Enter a 2 to play Game 1 or a 3 to play Game 2. Or enter 4 to quit." << endl;
cin >> num;
if (num == 2)
{
cout << "Welcome to Game 1!" << endl;
cout << "User, enter a random number between " << min << " and " << max << " : "; cin >> userNum;
systemGuess = rand() % 100 + 1;
do
{
cout << "System, guess the user's number between " << min << " and " << max << ": " << systemGuess << endl;
cin.get();
++tries;
if (systemGuess > max || systemGuess<min)
{
cout << "I said guess a number between " << min << " and " << max << " stupid." << endl;
}
if (systemGuess > userNum)
{
cout << "Too high. Guess lower." << endl;
prevMax = systemGuess;
systemGuess = rand() % (prevMax - prevMin) + prevMin;
if (systemGuess == prevMin)
systemGuess++;
}
else if (systemGuess < userNum)
{
cout << "Too low. Guess higher." << endl;
prevMin = systemGuess;
systemGuess = rand() % (prevMax - prevMin) + prevMin;
if (systemGuess == prevMin)
systemGuess++;
}
} while (systemGuess != userNum);
cout << systemGuess << endl;
cout << " I guessed it right! It took me " << tries << " guess(es). " << endl;
}
systemNum = rand()% 100 + 1;
//Beginning of second game
if (num == 3)
{
do
{
cout << "Welcome to Game 2!" << endl;
cout << "User, try to guess the computer's number that's between " << min << " and " << max << " . " << endl;
cout << "Enter your guess." << endl;
cin >> userGuess;
tries++;
if (userGuess > systemNum)
{
cout << "Too high. Guess lower." << endl;
cin >> userGuess;
}
else if (userGuess < systemNum)
{
cout << "Too low. Guess higher." << endl;
cin >> userGuess;
}
else
{
cout << "Correct! It took you long enough! Lol... " << endl;
cin >> userGuess;
}}
while (userGuess != systemNum);
}else if(num==4)return 0;
else{
cout<<"Invalid choice!";
system("pause");
return 1;
}
//print highscores
system("pause");
return 0;
}