#include<iostream>
#include<conio.h>
#include <chrono>
#include <ctime>
using namespace std;
typedef std::chrono::high_resolution_clock Clock;
/*struct*/ class Car
{
private:
int carYear;
string carMake;
string carModel;
int carSpeed;
float carGallons;
public:
Car(int cY = 0, string cMa = "", string cMo = "", int cS = 0, float cG = 10)
{
carYear = cY;
carMake = cMa;
carModel = cMo;
carSpeed = cS;
carGallons = cG;
}
Car()
{
carMake = "Bugatti";
carYear = 2020;
carModel = "Chiron";
}
int getCarYear() { return carYear; }
string getCarMake() { return carMake; }
string getCarModel() { return carModel; }
int getCarSpeed() { return carSpeed; }
float getCarGallons() { return carGallons; }
void setCarSpeed(int cS) { carSpeed = cS; }
void setCarGallons(float cG) { carGallons = cG; }
void accelerate()
{
startCar();
if(carGallons>0)
{
carSpeed += 5;
carGallons -= .5;
}
else if (carGallons < 0)
{
carGallons = 0;
cout << "Please refill tank!";
}
}
void brake()
{
startCar();
if(carSpeed>0&&carGallons>0)
{
carSpeed -= 5;
carGallons -= .2;
}
else if(carSpeed<0&&carGallons<0)
{
carSpeed = 0;
cout << "Your car isn't moving!";
}
}
void fillUP()
{
if (carSpeed > 0)
{
cout << "The car is still moving!";
}
else if(carSpeed==0)
{
if (carGallons > 22)
{
cout << "Car is full!";
carGallons = 22;
}
else
{
carGallons += .2;
}
}
}
void startCar(bool carOn=true)
{
while (true)
{
std::chrono::system_clock::time_point then;
auto now = std::chrono::system_clock::now();
auto duration = now - then;
then = now;
if (false) return;
{
auto s = std::chrono::duration_cast<std::chrono::duration<double>>(duration);
carGallons -= s.count() * .05f;
}
}
}
};
int main()
{
bool carOn = false;
Car userCar(2020, "Bugatti", "Chiron");
cout << "\nStart your new " << userCar.getCarYear()<<" "<< userCar.getCarMake() <<" "<< userCar.getCarModel()<<"!";
cout << "\nHit O to start your Engine!";
char ch;
cin >> ch;
if (ch== 'o'|| ch=='O') {
bool carOn = true;
cout << "\nCar is now on! Safe driving!\n";
int c = 0;
while (1)
{
c = 0;
switch (c = _getch())
{
case 32:
userCar.fillUP();
break;
case 72:
cout << userCar.getCarSpeed() << " " << userCar.getCarGallons();
userCar.accelerate();
break;
case 80:
userCar.brake();
break;
case 75:cout << "\nleft"; break;
case 77:cout << "\nright"; break;
default:
cout << " ";
}
}
}
else
{
cout << "\nCar is not on!";
}
return 0;
}
I'm running into an issue where after taking input from the user to turn on their car the inputs freeze up and the switch doesn't accept any other inputs. I know it has something to do with how I'm calling my functions inside the switch but I'm at a loss for how to correct it. Also, I'm fairly certain I've incorrectly implemented my clock inside startCar, it's supposed to subtract gas while the car is on.
Related
I'm not too sure if questions of this sort is allowed on stackoverflow but here it goes. I finished up this assignment to calculate reverse polish expressions with a small set of operators. All the tests passed and I have already submitted the assignment. I was wondering if you guys had any suggestions where I could improve on the code that could be applied to my future assignments/projects.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class TheStack
{
public:
void push(double d1);
double pop();
int getNodeTracker();
private:
struct Node
{
double data;
Node* next;
};
Node* bottom = NULL;
Node* top = NULL;
Node* newP = NULL;
int nodeTracker = 0;
};
void TheStack::push(double d1)
{
newP = new Node;
newP->data = d1;
newP->next = NULL;
if (bottom == NULL)
{
bottom = top = newP;
top->next = NULL;
}
else
{
newP->next = top;
top = newP;
}
nodeTracker += 1;
}
double TheStack::pop()
{
Node* tempP;
double tempD;
if (top == NULL)
{
cout << "The stack is empty." << endl;
}
else
{
tempP = top;
tempD = tempP->data;
top = top->next;
delete(tempP);
nodeTracker -= 1;
return(tempD);
}
}
int TheStack::getNodeTracker()
{
return nodeTracker;
}
bool isOperand(string s1);
bool isOperator(string s1);
double operate(string s1, double d1, double d2);
int processor(string str);
bool validString(string str);
int main()
{
// getting user input
string str;
getline(cin, str);
// input loop
while (str != "0")
{
processor(str);
cout << endl;
getline(cin, str);
}
// end program
return 0;
}
bool isOperand(string s1)
{
try
{
stod(s1);
}
catch (...)
{
return false;
}
return true;
}
bool isOperator(string s1)
{
string validOps[4] = { "+", "-", "*", "/" };
for (int i = 0; i < 4; i++)
{
if (s1 == validOps[i])
{
return true;
}
}
return false;
}
double operate(string s1, double d1, double d2)
{
char op = s1[0];
switch (op)
{
case '+':
return d1 + d2;
case '-':
return d1 - d2;
case '*':
return d1 * d2;
case '/':
return d1 / d2;
}
}
bool validString(string str)
{
for (int i = str.size()-1; i >= 0; i--)
{
if (str[i] == '=')
{
return true;
}
}
return false;
}
int processor(string str)
{
TheStack stacklist;
istringstream iss(str);
string streamVar;
iss >> streamVar;
// checks if expression has = sign
if (!validString(str))
{
cout << "Error: Please input valid expression." << endl;
return -1;
}
// builds and operates upon stack
while (streamVar != "=")
{
if (isOperand(streamVar))
{
stacklist.push(stod(streamVar));
}
else if (isOperator(streamVar))
{
if (stacklist.getNodeTracker() > 1)
{
double d2 = stacklist.pop();
double d1 = stacklist.pop();
if (streamVar == "/" && d2 == 0)
{
cout << "Error: Division by 0." << endl;
return -1;
}
double result = operate(streamVar, d1, d2);
stacklist.push(result);
}
else
{
cout << "Error: Too many operators." << endl;
return -1;
}
}
iss >> streamVar;
}
// operand error case
if (stacklist.getNodeTracker() > 1)
{
cout << "Error: Too many operands." << endl;
return -1;
}
// output
cout << stacklist.pop() << endl;
return 0;
}
I am a beginner with C++ and have tried a few different things, but no matter what I try it doesn’t seem to recognize when a card has already been drawn...
I have tried to utilize to bool isDrawn, but after a few attempts of that with no success I am not 100% sure where to go from here
class Card {
public:
string suitName;
int cardNumber;
void printCard() {
if (cardNumber == 1) {
cout << "Ace";
} else if (cardNumber == 11) {
cout << "Jack";
} else if (cardNumber == 12) {
cout << "Queen";
} else if (cardNumber == 13) {
cout << "King";
} else
cout << cardNumber;
cout << " of " << suitName << endl;
}
bool isDrawn = false;
};
class Deck {
public:
Card deck[52];
void makeDeck(){
int counter = 0;
string suits[] = { "Spades", "Hearts", "Clubs", "Diamonds" };
string face[] = { "Ace", "Jack", "Queen", "King" };
for (int i = 0; i <= 3; i++) {
for (int j = 0; j < 13; j++) {
deck[counter].isDrawn = false;
deck[counter].cardNumber = (j + 1);
deck[counter].suitName = suits[i];
counter++;
}
}
}
Card drawCard() {
int randcard;
do {
randcard = rand() % 52;
} while (deck[randcard].isDrawn == true);
return deck[randcard];
}
};
class Player {
public:
vector<Card> hand;
void setName(string s){
name = s;
}
string printName(){
return name;
}
void printHand() {
for (int i = 0; i < hand.size(); i++){
hand.at(i).printCard();}
}
private:
string name;
};
int main() {
Deck my_deck;
Player p1;
p1.setName("HAL 9000");
cout << p1.printName() << endl;
my_deck.makeDeck();
p1.hand.push_back(my_deck.drawCard());
p1.hand.push_back(my_deck.drawCard());
p1.hand.push_back(my_deck.drawCard());
p1.printHand();
cout << endl;
}
I have problem when i try to change my 2 private class variables in FBullCowGame.h .It seems like constructor is calling function Reset() [Located in FBullCowGame.cpp] but Reset() function wont change integers MyMaxTries & MyCurrentTry.I'm new to c++ so probably it's something obvious but i can't find it .
This is main.cpp
#include <iostream>
#include <string>
#include "FBullCowGame.h"
using FText = std::string;
void PrintIntro();
void PlayGame();
FText GetGuess();
FText PrintGuess();
FBullCowGame BCGame;//Dodeljujemo naziv u main-u FBullCowGame-u , takodje ako ima neki kod u constructoru on ga izvrsava pri ovaj deklaraciji
bool AskToPlayAgain();
int main()
{
bool bPlayAgain = false;
do {
PrintIntro();
PlayGame();
bPlayAgain = AskToPlayAgain();
}
while (bPlayAgain);
return 0;
}
void PrintIntro()
{
//Define constant var
constexpr int WORD_LENGHT = 6;
//Welcome to the player and asking the guess
std::cout << "Welcome to Bulls and Cows\n";
std::cout << "Can you guess my " << WORD_LENGHT;
std::cout << " letter isogram word?\n";
}
void PlayGame()
{
BCGame.Reset();
int MaxTries = BCGame.GetMaxTries();
//Looping for guesses
for (int i = 1; i <= MaxTries; i++)
{
FText Guess = GetGuess();
//Repeat the guess back to them
std::cout << "Your guess is: " << Guess << std::endl;
std::cout << std::endl;
}
return;
}
FText GetGuess()
{
int CurrentTry = BCGame.GetCurrentTry();
//Player enters their guess
std::cout << std::endl << "Try " << CurrentTry << ".What is your guess?\n";
FText Guess = "";
std::getline(std::cin, Guess);
return Guess;
}
bool AskToPlayAgain()
{
FText Response = "";
std::cout << "Do you want to play again (y/n) ?" << std::endl;
std::getline(std::cin, Response);
return (Response[0] == 'y') || (Response[0] == 'Y');
}
FBullCowGame.h /
#pragma once
#include <string>
class FBullCowGame {
public:
FBullCowGame();//Constructor izvrsava se kod u njemu pri deklaraciji BCGame u nasem slucaju
int GetMaxTries() const;
int GetCurrentTry()const;
bool IsGameWon()const;
void Reset();
bool CheckGuessValidity(std::string);
private:
//Compile time values gets overwritten by run time values in Constructor
int MyMaxTries;
int MyCurrentTry;
};
And FBullCowGame.cpp /
#include "FBullCowGame.h"
FBullCowGame::FBullCowGame()
{
//Run time values
Reset();
}
void FBullCowGame::Reset()
{
constexpr int MAX_TRIES = 8;
int MyMaxTries = MAX_TRIES;
int MyCurrentTry = 1;
return;
}
int FBullCowGame::GetMaxTries ()const
{
return MyMaxTries;
}
int FBullCowGame::GetCurrentTry ()const
{
return MyCurrentTry;
}
bool FBullCowGame::IsGameWon ()const
{
return false;
}
bool FBullCowGame::CheckGuessValidity(std::string)
{
return false;
}
You are shadowing your member variables with function-local variables that happen to have the exact same name.
void FBullCowGame::Reset()
{
constexpr int MAX_TRIES = 8;
int MyMaxTries = MAX_TRIES;
int MyCurrentTry = 1;
return;
}
Just assign to your member variables, but don't redeclare them
void FBullCowGame::Reset()
{
constexpr int MAX_TRIES = 8;
MyMaxTries = MAX_TRIES;
MyCurrentTry = 1;
}
I am writing a very simple game simulator (does not use classes). From the main() function, I successfully access one of my functions, but another function call throws the error: 'No matching function for call to simGame'.
Any ideas why this is happening?
Code:
...
float rollDice() {
default_random_engine randomGenerator(time(NULL));
uniform_real_distribution<float> rollDice(0.0f, 1.0f);
float roll = rollDice(randomGenerator);
return roll;
}
string simGame(string p1, string p2, int p1Health, int p2Health, int p1Attack, int p2Attack) {
// Game State
bool gameOver = false;
float attack = rollDice();
int pl1 = 0;
int pl2 = 1;
int turn = pl1;
int defenderHealth = p2Health;
int attackerAttack = p1Attack;
while ((p1Health > 0) && (p2Health > 0)) {
if (attack > 0.3) {
defenderHealth -= attackerAttack;
}
turn = -turn + 1;
if (turn == 0) {
defenderHealth = p2Health;
attackerAttack = p1Attack;
} else {
defenderHealth = p1Health;
attackerAttack = p2Attack;
}
}
turn = -turn + 1;
if (turn == 0) {
return p1;
} else {
return p2;
}
return 0;
}
int setHealth(int botNum, int botHealth) {
int totalHealth = botNum * botHealth;
return totalHealth;
}
int main() {
// bot types
int drWhosAndCompanions;
int ricksAndMortys;
// Attributes
int rmHealth = 10;
int dcHealth = 15;
int rmAttack = 15;
int dcAttack = 10;
int totalRMHealth;
int totalDocHealth;
cout << "How many Ricks and Mortys?" << endl;
cin >> ricksAndMortys;
cout << "How many Dr Whos and Companions?" << endl;
cin >> drWhosAndCompanions;
// Starting Vals
totalRMHealth = setHealth(ricksAndMortys, rmHealth);
totalDocHealth = setHealth(drWhosAndCompanions, dcHealth);
cout << "You have chosen " << ricksAndMortys << " Ricks and Mortys and " << drWhosAndCompanions << " Dr. Whos and Companions.\n";
string res;
res = simGame(ricksAndMortys, drWhosAndCompanions, rmHealth, dcHealth, rmAttack, dcAttack);
return 0;
}
Its simple
Your function definition has this prototype
simGame(string, string, int, int, int, int);
But you are passing
simGame(ricksAndMortys, drWhosAndCompanions, rmHealth, dcHealth, rmAttack, dcAttack);
In which ricksAndMortys and deWhosAndCompanions are int type
So change their data type to string
In main function
// bot types
int drWhosAndCompanions;
int ricksAndMortys;
Should be
// bot types
string drWhosAndCompanions;
string ricksAndMortys;
I am getting compile errors in my C++ project. On my friend's computer I get no errors but on mine I get the following:
On line 129 - "Function Definition does not declare parameters "
On line 137 - "'seats' was not declared in this scope"
I am running Code::blocks 10.05 on Windows 7.
Here is my code (with line numbers indicated by comments):
#include <iostream>
#include "Seat.h"
using namespace std;
class Plane
{
public:
int viewSeat(int sNum) {
if (seats[sNum].isFree()) {
return 0;
} else {
//cout << "Debug (Plane::viewSeat(sNum) called)";
string seatMess = "";
switch (seats[sNum].getState()) {
case 1:
seatMess = " is reserved for ";
break;
case 2:
seatMess = " has been checked in by ";
break;
}
cout << "(X) Seat ";
cout << seats[sNum].getCode();
cout << seatMess;
cout << seats[sNum].getFName() << " " << seats[sNum].getLName() << "\n";
return 1;
}
}
void viewAll() {
for (int x = 0; x < numOfSeats; x++) {
if ((seats[x].getState() == 0)) {
cout << "Seat " << seats[x].getCode() << " is free\n";
} else {
viewSeat(x);
}
}
}
void viewFree() {
int freeSeats = 0;
for (int x = 0; x < numOfSeats; x++) {
if ((seats[x].getState() == 0)) {
cout << "Seat " << seats[x].getCode() << " is free\n";
freeSeats++;
}
}
cout << "Found " << freeSeats << " free seats\n";
}
void freeSeat(int sNum) {
seats[sNum].emptySeat();
}
string getCode(int sNum) {
return seats[sNum].getCode();
}
int reserveSeat(int sNum, string fName, string lName, int age, int cType, string business = "") {
if (seats[sNum].isFree()) {
seats[sNum].setFName(fName);
seats[sNum].setLName(lName);
seats[sNum].setAge(age);
seats[sNum].setType(cType);
seats[sNum].setState(1);
seats[sNum].setBusiness(business);
return 1;
} else {
return 0;
}
}
int checkSeat(string lName, string seatCode) {
int found = 0;
for (int x = 0; x < (sizeof(seats) / sizeof(Seat)); x++) {
if ((seats[x].getCode() == seatCode) && (seats[x].getLName() == lName)) {
found = 1;
seats[x].setState(2);
return 1;
}
}
return 0;
}
int calcTake() {
int seatPrice = 5;
int totalTake, totalSeats = 0, totalWestern = 0, totalBusiness = 0, totalStandard = 0;
for (int x = 0; x < numOfSeats; x++) {
if ((seats[x].getState() != 0)) {
int cType = seats[x].getType();
int thisSeat;
if (cType == 1) {
// discount for western`
thisSeat = 0.75 * seatPrice;
totalWestern++;
} else if (cType == 2) {
// discount for business
thisSeat = 0.8 * seatPrice;
totalBusiness++;
} else {
thisSeat = 0.95 * seatPrice;
totalStandard++;
}
totalTake = totalTake + thisSeat;
totalSeats++;
}
}
return totalTake;
}
int isFree(int sNum) {
if (seats[sNum].isFree()) {
return 1;
} else {
return 0;
}
}
private:
// Line 129 ("Function Definition does not declare parameters"):
Seat seats[32] { {"1A"}, {"1B"}, {"1C"}, {"1D"},
{"2A"}, {"2B"}, {"2C"}, {"2D"},
{"3A"}, {"3B"}, {"3C"}, {"3D"},
{"4A"}, {"4B"}, {"4C"}, {"4D"},
{"5A"}, {"5B"}, {"5C"}, {"5D"},
{"6A"}, {"6B"}, {"6C"}, {"6D"},
{"7A"}, {"7B"}, {"7C"}, {"7D"},
{"8A"}, {"8B"}, {"8C"}, {"8D"}
};
// Line 137 ("'seats' was not declared in this scope"):
int numOfSeats = sizeof(seats) / sizeof(Seat);
};
I think you have missed =
Seat seats[32] = { {"1A"}, {"1B"}, {"1C"}, {"1D"},..