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;
Related
#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.
I have 3 files, book.h, book.cpp, bookdriver.cpp. I want to know if the ISBNs in a list are found in the array using binary search.
book.h:
using namespace std;
ofstream fout("output2.txt");
class Book
{
string author; // A string for the name of the author
string title; //A string for the book title
int ISBN; //A long integer for the ISBN
public:
Book(); //A default constructor
void print();
int getISBN() const; //A const function GetISBN that returns the integer containing the ISBN.
int binary_search(Book, int, int, int);
};
book.cpp- also includes print function which uses fout
#include "book.h"
//iterative binary search function, returns location of ISBN in array if present
int Book::binary_search(Book arr[], int x, int n, int ISBN)
{
while (n >= x)
{
int midpt = x + (n - x) / 2;
//if ISBN is in midpoint
if (arr[midpt].getISBN() == ISBN)
{
return midpt;
}
//if ISBN is greater than midpoint, ignore left side of array
if (arr[midpt].getISBN() < ISBN)
{
x = midpt + 1;
}
//if ISBN is smaller, ignore right side of array
else
{
n = midpt - 1;
}
}
//if ISBN not present
return -1;
}
bookdriver.cpp
#include "book.h"
const int num = 10; //number of book objects the array should hold *can be changed*
int main()
{
Book book_array[num] = {}; //array can hold num book objects
for (int c = 0; c < num; c++)
{
book_array[c] = Book();
book_array[c].getData(data); //reading book information
}
//read file
ifstream fin("bookISBN.txt");
int find_ISBN;
while (fin >> find_ISBN)
{
bool match = false;
int count = 0;
int result = binary_search(book_array[10], 0, num - 1, find_ISBN); //error here
if (result == -1) //if ISBN not found
{
fout << "Sorry, the ISBN " << find_ISBN << " is not found." << endl;
}
else
{
fout << "The ISBN " << find_ISBN << " is found in the system!" << endl;
}
count++;
}
return 0;
}
I'm using fout in both book.cpp and bookdriver.cpp so I have ofstream fout (output2.txt) in the header but I'm getting linker errors(Error LNK2005) in vs.
I think because of the one definition rule, fout is defined twice?
Here's a start:
#include <iostream>
#include <fstream>
using namespace std;
const int num = 2;
class Book
{
public:
Book(){};
string author;
string title;
int ISBN = 0;
int data;
};
int binary_search (Book arr[num], int x, int n, int ISBN, int overflow)
{
int mid = (x + n) / 2;
if (x == mid || n == mid)
overflow++;
if (overflow > 100)
return false;
if (arr[mid].ISBN > ISBN)
return binary_search(arr, x , mid, ISBN, overflow);
else if (arr[mid].ISBN < ISBN)
return binary_search(arr, mid, n , ISBN, overflow);
return true;
}
int main() {
ofstream fout("output2.txt");
ifstream fin("bookISBN.txt");
int find_ISBN;
Book book1;
book1.title = "Alice in Wonderland";
book1.author = "C.S. Lewis";
book1.ISBN = 1;
Book book2;
book2.title = "Wuthering Heights";
book2.author = "Emily Bronte";
book2.ISBN = 2;
Book book3;
book3.title = "Moby Dick";
book3.author = "Herman Melville";
book3.ISBN = 25;
Book book_array[num] = {book1, book2};
while (fin >> find_ISBN)
{
int result = binary_search(book_array, 0, num, find_ISBN, 0);
if (result == false)
{
fout << "Sorry, the ISBN " << find_ISBN << " is not found." << endl;
}
else
{
fout << "The ISBN " << find_ISBN << " is found in the system!" << endl;
}
}
fin.close();
fout.close();
return 1;
}
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;
}
in the following code I have a for loop in my main function. Since a function can't return 2 values, what are some ways I could create a function, or functions, to remove it from my main function. Thanks!
#include <iostream>
#include <cmath>
using namespace std;
int getNumberExercises();
int getScores(int numberOfExercises);
int getPoints(int numberOfExercises);
double roundToTenth(double number);
double calcPercentage(int totalScore, int totalPoints);
void getTotal(int totalScore, int totalPoints, double scorePercentage);
int main() {
int numberOfExercises = 0;
int totalScore = 0;
int totalPoints = 0;
double scorePercentage = 0.0;
numberOfExercises = getNumberExercises();
for (int i = 1; i <= numberOfExercises; i++) {
totalScore += getScores(i);
totalPoints += getPoints(i);
}
scorePercentage = calcPercentage(totalScore, totalPoints);
getTotal(totalScore, totalPoints, scorePercentage);
return 0;
}
int getNumberExercises() {
int numberOfExercises;
cout << "How many exercises to input? ";
cin >> numberOfExercises;
cout << endl;
return numberOfExercises;
}
int getScores(int i) {
int score = 0;
cout << "Score received for exercise " << i << ": ";
cin >> score;
return score;
}
int getPoints(int i) {
int points = 0;
cout << "Total points possible for exercise " << i << ": ";
cin >> points;
cout << endl;
return points;
}
double roundToTenth(double number) {
return floor(number * 100 + 0.5) / 100;
}
double calcPercentage(int totalScore, int totalPoints) {
double scorePercentage = (double) totalScore / totalPoints * 100;
return scorePercentage;
}
void getTotal(int totalScore, int totalPoints, double scorePercentage) {
cout << "Your total is " << totalScore << " out of " << totalPoints << ", or " << roundToTenth(scorePercentage) << "%";
}
Either typedef a std::pair to a descriptive name, or create your own type to hold the things you want to return:
using ScorePointPair = std::pair<int, int>; // C++11
typedef std::pair<int, int> ScorePointPair; // pre C++11
Or
struct ScorePointPair
{
int score;
int points;
};
Then simply return this from your function (by value):
ScorePointPair fun()
{
// Loop etc...
return {score, points};
};
I would recommend the custom type (struct/class) approach, as this tends to be more maintainable.
To return multiple values use pass by pointer:
void modify(int *val1, int *val2)
{
*val1 = 46;
*val2 = 100;
}
In caller:
int a, b;
modify(&a, &b);
Now a will be 46, and b will be 100. This is because the address is copied, rather than the actual variable, which is what happens in pass by value.
So if you want to find the number of occurences of tabs and commas in a file:
void findtabcomma(const char *fn, int *ncomma, int *ntab)
{
FILE *fp;
int c;
if (fp = fopen(fn, "r")) {
while ((c = getc(fp)) != EOF) {
if (c == '\t')
++(*ntab);
if (c == ',')
++(*ncomma);
}
fclose(fp);
}
}
You can use the function like this:
int c, t;
findtabcomma(filenam, &c, &t);
printf("Commas: %d\nTabs: %d", c, t);
And in C++, you can use reference variables. So the findtabcomma function could be rewritten as:
void findtabcomma(const char *fn, int &ncomma, int &ntab)
{
FILE *fp;
int c;
if (fp = fopen(fn, "r")) {
while ((c = getc(fp)) != EOF) {
if (c == '\t')
++ntab;
if (c == ',')
++ncomma;
}
fclose(fp);
}
}
And used like this:
int c, t;
findtabcomma(filenam, c, t);
printf("Commas: %d\nTabs: %d", c, t);
Notice how there are no more *s and &s with C++ references.
You can create a function that either returns an array of type int of size 2 such as
int* functionName(arg1, arg2)
array[0] = totalScore;
array[1] = totalPoints;
return array;
or you could pass in the values by reference by doing something like
void functionName(&arg1, &arg2)
What passing by reference does is it passes the ADDRESS of the variable and then modifies the variable directly instead of creating a copy and passing it into the function.
You can use reference in the argument list to return data
int fun(); can be coded as void fun(int& )
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"},..