So I'm working on a code to program a Car Instrument Simulator and I'm supposed to have a switch statement for a menu to: Show gauges, ask how far they are to Driving, ask how much Gas to add, and to Exit. I got it to show the menu but when I press one of the options it doesn't do anything. I would like someone to help me to figure out what I'm missing and not saying to help me do it because I want to learn so next time I won't have the same problem, been working on it for a while now and even looked up some videos about switch statements but I'm just not getting it.
#include <iostream>
#include <string>
using namespace std;
void printmenu();
class FuelGauge
{
private:
int CurrentFuel;
public:
FuelGauge();
~FuelGauge();
FuelGauge(int g)
{
CurrentFuel = g;
}
int getCurrentFuel()
{
return CurrentFuel;
}
void IncrementFuel()
{
int gas;
cout << "How much fuel are you putting in? " << endl;
cin >> gas;
for (int fuel = gas; gas > 0; gas--) {
CurrentFuel++;
}
}
void DecrementFuel()
{
if (CurrentFuel > 0)
CurrentFuel--;
}
};
FuelGauge::FuelGauge()
{
}
FuelGauge::~FuelGauge()
{
}
class Odometer
{
private:
int CurrentMileage;
FuelGauge* fuel;
public:
Odometer();
~Odometer();
Odometer(int miles, FuelGauge* f)
{
CurrentMileage = miles;
fuel = f;
}
int getCurrentMileage()
{
return CurrentMileage;
}
void incrementCurrentMileage()
{
if (CurrentMileage < 999999)
CurrentMileage++;
else
CurrentMileage = 0;
}
void decrementCurrentMileage()
{
if (CurrentMileage > 24)
CurrentMileage--;
(*fuel).DecrementFuel();
}
};
Odometer::Odometer()
{
}
Odometer::~Odometer()
{
}
int main()
{
FuelGauge fuel(15);
Odometer odo(0, &fuel);
int n = 0;
while (n != 5) {
printmenu();
cin >> n;
switch (n) {
case 1:
fuel.getCurrentFuel();
break;
case 2:
odo.getCurrentMileage();
break;
case 3:
break;
case 4:
fuel.IncrementFuel();
break;
default:
break;
}
return 0;
}
}
void printmenu() {
cout << "1. Show current fuel " << endl;
cout << "2. Show current status of the odometer " << endl;
cout << "3. How far are you going? " << endl;
cout << "4. How much gass are you putting in? " << endl;
}
What do you plan to observe? You call some methods that return values without any side effects, and you don't do anything with those values: you get lost them immediately. You should probably output them:
cout << fuel.getCurrentFuel();
Related
i'am begginner in C++, i want to ask question about what's wrong about my coding, when i doing my work then found out problem i can't solve in searching function, there's no error notice or anything from visual studio but my function still didn't work,
sorry for my bad english.
here is my full code
#include <iostream>
#include <cstdlib>
#define MAX 5
using namespace std;
struct College {
int nim;
string name;
}mahasiswa;
struct queue {
College college[MAX];
int start,end = - 1;
}antrean;
void init() {
antrean.start= -1;
antrean.end = -1;
}
bool full() {
if (antrean.end== MAX - 1) {
return true;
}
else {
return false;
}
}
bool empty() {
if (antrean.end== -1) {
return true;
}
else {
return false;
}
}
void tampilData() {
int i;
if (!empty()) {
for (i = antrean.start; i < antrean.end; i++)
{
cout<<antrean.college[i].nim<<" | ";
cout << antrean.college[i].name << " | ";
cout << "\n";
}
}
cout<<"\n";
}
void inQueue() {
tampilData();
int elemennim;
string elemenname;
if (!full()) {
cout << "Input your NIM : ";
cin >> elemennim;
cout << "\n";
cout << "Input your name: ";
cin >> elemenname;
cout << "\n";
cout << "Succefully\n";
antrean.college[antrean.end].nim = elemennim;
antrean.college[antrean.end].name = elemenname;
antrean.end++;
}
else
{
cout << "Queue Penuh\n";
}
}
and this the error function i cant solve,
void searching(int key) {
for (int i = 0; i <= antrean.start; i++)
{
if (key == antrean.college[i].nim) {
cout << "Element found in index " << i;
}
else
{
cout << "Element not found\n";
}
cout << antrean.college[i].nim;
}
}
int main() {
int choice, elemen;
init();
cout << "Demo Queue dengan Linear Array" << endl;
do {
tampilData();
cout << "\nMenu Utama\n";
cout << "==============\n";
cout << "[1] Init \n[2] InQueue \n[3] Searching \n[4] out \n";
cout << "==============\n";
cout << "\nMasukkan pilihan: "; cin >> choice;
cout << "==============\n";
switch (choice) {
case 1: init(); break;
case 2: inQueue(); break;
case 3: cout << "masukkan NIM yang ingin dicari \n";
cin >> choice;
searching(choice); break;
} while (choice != 0);
return 0;
}
please help me, thank you very much
guys! Down here is the code that I have for my Bank assignment. It ran well when I chose Case 1 to check the Balance. However, when I chose Case 2 for Depositing, the program crashes right after entering the amount of deposit. I looked through the code but I'm not sure where the problem came from. However, the program seems to run ok when executed on cpp.sh website and only crashes on Visual Studio. Is it because of my code or my compiler?
#include <iostream>
#include <string>
using namespace std;
class account {
private:
double AccountActivity[200];
double balance;
int numTransactions;
public:
//declaration
};
void account::test() {
account a;
int choice;
bool menu = true;
double amount = 0;
while (menu = true) {
choice = a.getUserChoice();
switch (choice) {
case 1:
a.print();
break;
case 2:
cout << "\n\nPlease enter the amount of deposit: " << endl;
cin >> amount;
a.deposit(amount);
break;
case 3:
cout << "\n\nPlease enter the amount of withdrawal: " << endl;
cin >> amount;
a.withdraw(amount);
break;
case 4:
cout << "The largest deposit is: " << a.getLargest() << endl;
default:
cout << "Please choose from 1 to 4" << endl;
break;
}
}
}
int account::getUserChoice() {
//do something
}
double account::getLargest()
{
//do something
}
void account::print() {
cout << "Your balance is: $" << balance;
cout << "\n\n";
}
account::account() {
balance = 0;
}
void account::deposit(double amount) {
if (numTransactions < 200)
{
AccountActivity[numTransactions] = amount;
numTransactions++;
balance += amount;
}
}
void account::withdraw(double amount) {
if (balance < amount)
cout << "Insufficient balance" << endl;
else
{
if (amount >= 0 && numTransactions < 200)
{
AccountActivity[numTransactions] = -amount;
numTransactions++;
balance -= amount;
}
}
}
int main() {
//do something
}
numTransactions is not initialized. Using an uninitialized value to index into an array is undefined behavior.
In your account constructor account::account() set numTransactions to 0
Oh yeah: while (menu = true) { try while(menu) - but then you don't change menu inside the loop so you might as well make it while(1) {
//Benjamin McKinney
//CSCI 2010-10
//Spring 2015
//PASS 3
//Programmed on Windows 8.1 using Visual C++ 2010 Express
//This program plays the game MasterMind
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
struct Player
{
string Name;
int HighScores[6];
bool CheatOn;
};
struct Board
{
int NumHoles;
int Holes[6];
};
struct Guess
{
int Count;
int NumHoles;
int Holes;
};
void printHighScores(string);
void readHighScore(string);
void updateHighScore(string, int);
string getPlayer();
int getBoard();
void playGame(string);
void menu(string);
int main()
{
Player p;
srand((unsigned int)time(0));
cout << "!!! Benjamin McKinney's Master-MasterMind!!!\n";
cout << "--------------------------------------------\n";
getPlayer();
menu(p.Name);
cout << "Goodbye, " << p.Name << endl;
printHighScores(p.Name);
cout << "----------------------------------------------\n";
cout << "!!! Benjamin McKinney's Master-MasterMind!!!\n";
system("PAUSE");
return 0;
}
void printHighScores(string name)
{
return;
}
void readHighScore(string)
{
return;
}
void updateHighScore(string, int)
{
return;
}
string getPlayer()
{
Player p;
cout << "What is your name?\n";
cin >> p.Name;
cout << "Welcome, " << p.Name << endl;
p.CheatOn = false;
readHighScore(p.Name);
return p.Name;
}
int getBoard()
{
Board b;
cout << "Enter the number of holes you would like: ";
cin >> b.NumHoles;
if(b.NumHoles > 6 || b.NumHoles < 1)
{
cout << "Error! You must pick a number between 1 and 6! Try again!\n";
}
for(int i=0;i<b.NumHoles;i++)
{
b.Holes[i] = rand() % 2 + 1;
}
return b.NumHoles;
}
void playGame(string)
{
Player p;
Board b;
Guess g;
getBoard();
g.Count=0;
for(int i=0;i<b.NumHoles;i++)
{
cout << "Enter your guess for the row\n";
if(p.CheatOn == true)
{
for(int a=0;a<(sizeof(b.Holes)-1);a++)
{
cout << b.Holes[a];
}
}
cout << "Enter your guess for hole " << i << ": ";
cin >> g.Holes;
g.Count++;
}
return;
}
void menu(string)
{
Player p;
char choice;
cout << "Please choose an option below:\n";
cout << "\t P)lay\n\t Q)uit\n\tChoice: ";
cin >> choice;
if(choice == 'P')
playGame(p.Name);
else
if(choice == 'Q')
return;
else`enter code here`
if(choice == 'C')
{
p.CheatOn = true;
playGame(p.Name);
}
}
Ignore the three HighScore functions, but otherwise I can't get this to work... "Run-Time Check Failure #3 - The variable 'b' is being used without being initialized." is the main issue that I'm having. If anyone can help me I would really appreciate it. Thanks!
In the playGame function:
void playGame(string)
{
Player p;
Board b; // <----- uninitialized
// ...
for(int i=0;i<b.NumHoles;i++)
// ^^^^^^^^^^
you use b.NumHoles when you have never initialized b.
I guess you intended that getBoard() would magically have some effect on b but it doesn't. The getBoard function updates a local board but never does anything with it.
To fix this you could change getBoard to return the whole board:
Board getBoard()
{
Board b;
// set up b...
return b;
}
and then inside playGame:
Board b = getBoard();
There's another error just below:
for(int a=0;a<(sizeof(b.Holes)-1);a++)
The sizeof operator gives the size in bytes. You actually want the size in elements, so you need to divide by the element size:
a < (sizeof b.Holes / sizeof b.Holes[0])
I'm not sure what the -1 was meant to be doing either, this would just cause you to not output the last hole.
what i am trying to do is display my pointer to an array of objects. here is my main program, the function it crashes at is listAll(). if i only enter one object it works, but when i enter a second one it crashes. i am at a loss of what is going wrong. problem occurs after picking menuOption 1 twice and then trying to call list all. i see that the array size is not being increased..
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#include "fileStuff.h"
bool menu();
bool menuOptions(int option);
void fileIO();
void listAll(interact * obs, int arryO);
int main()
{
bool isRunning = true;
while (isRunning)
{
isRunning = menu();
}
return 0;
}
bool menu()
{
int option = 0;
cout << "1: add new backpack. " << endl
<< "2: delete a backpack "<< endl
<< "3: sort ascending by id " << endl
<< "4: sort descending by id " << endl
<< "5: list all backpacks " << endl
<< "6: quit" << endl;
cin >> option;
return menuOptions(option);
}
bool menuOptions(int option)
{
static int arrayO = 0;
static interact *obs = new interact[arrayO];
fileStuff test;
int tempBagId = 0, tempInvSpaces = 0, tempAmtOfItemsInInv = 0;
double tempInvMaxWeight = 0.0;
string tempBagType, tempBagCondish;
int t = 0 ;
int i = 0;
switch (option)
{
case 1:
cout << "bagId? ";
cin >> tempBagId;
cout << "How many inv spaces? ";
cin >> tempInvSpaces;
cout << "How much weight can the bag hold? ";
cin >> tempInvMaxWeight;
(obs + arrayO)->setBagId(tempBagId);
(obs + arrayO)->setInvSpaces(tempInvSpaces);
(obs + arrayO)->setInvMaxWeight(tempInvMaxWeight);
cout << "all stored" << endl;
arrayO++;
break;
case 2:
//listmanager delete one
//arrayO--;
break;
case 3:
//sort ascending by id
break;
case 4:
//sort descending by id
break;
case 5:
//list all
listAll(obs, arrayO);
break;
case 6:
obs = NULL;
delete obs;
return false;
break;
default:
break;
}
}
void listAll(interact * obs, int arryO)
{
int i = 0;
cout << i << endl;
cout << arryO << endl;
}
below is the gists of my class.
#include "listManager.h"
#include <iostream>
#include <string>
using namespace std;
interact::interact()
{
bagId = 0;
invSpaces = 0;
invMaxWeigt = 0;
}
void interact::setBagId(int id)
{
bagId = id;
}
void interact::setInvSpaces(int spaces)
{
invSpaces = spaces;
}
void interact::setInvMaxWeight(double weight)
{
invMaxWeigt = weight;
}
int interact::getBagId()
{
return bagId;
}
int interact::getInvSpaces()
{
return invSpaces;
}
double interact::getInvMaxWeight()
{
return invMaxWeigt;
}
You have:
static int arrayO = 0;
static interact *obs = new interact[arrayO];
This will create a dynamic array of 0 length. As Ben stated, the pointer will never change.
The crash is probably caused by trying to access it after increasing the index (arrayO++;), after that it will just be accessing out of bounds memory.
Your obs points to an array with size zero:
static int arrayO = 0;
static interact *obs = new interact[arrayO];
and never is changed to point to anything larger.
Therefore every attempt to subscript it is an array overrun.
I am making a basic text based RPG sorry if my question is stupid because i'm new to c++. So basically I have a small combat class that I have to link back and forth to from the map class so I had to forward declare my map class and it comes up with the error. BTW sorry there aren't any comments.
Here is the error: invalid use of incomplete type class Map
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Map;
class Player
{
public:
int health;
int damage;
int defense;
int gems=0;
string race;
string name;
string location;
};
class Enemy
{
public:
int ehealth;
int edamage;
int edefense;
int echoice;
};
class combat
{
public:
Map* mapobj;
int damagedealt;
Player playerobj;
Enemy enemeyobj;
string cchoice;
string retry;
void initial()
{
cout <<"A wild orc has appeared\n";
cout <<"What do you do?\n";
cout <<"---------------------------\n";
cout <<"|-------------------------|\n";
cout <<"|----Attack-----Defend----|\n";
cout <<"|-------------------------|\n";
cout <<"---------------------------\n";
cin >>cchoice;
this->battle();
};
void newturn()
{
cout <<"The orc is still alive!";
cout <<"What do you do?";
cout <<"\n---------------------------\n";
cout <<"|-------------------------|\n";
cout <<"|----Attack-----Defend----|\n";
cout <<"|-------------------------|\n";
cout <<"---------------------------\n";
cin >>cchoice;
this->battle();
};
void battle()
{
enemeyobj.echoice = rand() % 2;
if (enemeyobj.echoice= 1)
{
if (cchoice=="Attack")
{
playerobj.damage;
enemeyobj.ehealth=enemeyobj.ehealth-playerobj.damage;
cout <<"You did "<<playerobj.damage<<" points of damge to the enemey.\n";
if (enemeyobj.ehealth>0)
{
playerobj.health=enemeyobj.edamage-playerobj.health;
cout <<"The enemyattacked you. You now have "<<playerobj.health<<" health";
if (playerobj.health>0)
{
this->newturn();
}
else if (playerobj.health<=0)
{
cout << playerobj.name << "was killed\n";
cout << "Game Over";
}
}
else if (enemeyobj.ehealth<=0)
{
cout <<"You have defeated the orc!";
if (playerobj.location=="a")
{
mapobj->relaypointa();
}
}
}
else if (cchoice=="Defend")
{
damagedealt=enemeyobj.edamage-playerobj.defense;
playerobj.health=damagedealt-playerobj.health;
cout <<"You defend but the enemey was able to deal\n";
cout <<damagedealt<<" points of damage your health is\n";
cout <<playerobj.health;
if (playerobj.health>0)
{
this->newturn();
}
else if (playerobj.health<=0)
{
cout <<playerobj.name<<"was killed\n";
cout <<"Game Over";
}
}
}
else if (enemeyobj.echoice=2)
{
if (cchoice=="Attack")
{
damagedealt=enemeyobj.edefense-playerobj.damage;
enemeyobj.ehealth=enemeyobj.ehealth-damagedealt;
cout <<"You did "<<damagedealt<<" points of damage to the enemy";
if (enemeyobj.ehealth>0)
{
this->newturn();
}
else if (enemeyobj.ehealth<=0)
{
cout <<"You have defeated the orc!";
mapobj->relaypointa();
}
}
else if (cchoice=="Defend")
{
cout <<"Both parties defended";
this->newturn();
}
}
}
};
class Map
{
public:
combat combatobj;
string mchoice;
int espawn;
Player playerobj;
Enemy enemeyobj;
void relaypointaespawn()
{
playerobj.location=="relaypointa";
enemeyobj.ehealth = rand() % 50 + 100;
enemeyobj.edamage = rand() % 50 + 75;
enemeyobj.edefense = rand() % 50 + 50;
combatobj.initial();
}
void relaypointa()
{
cout <<"You have found yourself at the\n";
cout <<"mouth of a mighty river to the north\n";
cout <<"What do you want to do?\n";
}
void relaypointb()
{
playerobj.location=="relaypointb";
cout << "\n\n%%%%%%%%%%%%%%%%%%%%\n";
cout << "% %\n";
cout << "% #Wild North# %\n";
cout << "% %\n";
cout << "%%%%%%%%%%%%%%%%%%%%\n\n";
cout <<"You have entered the wild north this is where your journey starts\n";
cout <<"What would you like to do\n\n";
cin >> mchoice;
if (mchoice=="Travel")
{
cout <<"Where would you like to travel?\n";
cin >>mchoice;
if (mchoice=="North")
{
}
else if (mchoice=="East")
{
}
else if (mchoice=="South")
{
}
else if (mchoice=="West")
{
this->relaypointaespawn();
}
else
{
cout <<"Invalid command\n\n";
this->relaypointb();
}
}
}
void relaypointcespawn()
{
playerobj.location=="a";
enemeyobj.ehealth = rand() % 50 + 100;
enemeyobj.edamage = rand() % 50 + 75;
enemeyobj.edefense = rand() % 50 + 50;
espawn = rand() % 2;
}
};
Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.
A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.
The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.
I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.
class FooReader {
public:
/** Constructor */
FooReader() : d(new FooReaderPrivate(this)) { } // will not compile here
.......
private:
FooReaderPrivate* d;
};
====== In a separate file =====
class FooReaderPrivate {
public:
FooReaderPrivate(FooReader*) : parent(p) { }
private:
FooReader* parent;
};
The above will not pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.
This is because you need to show the at least decleration of the functions.
For workaround, create interface class with pure virtual methods for map class. Declare the functions that you are using ( as I see only relaypointa) then put this interface class in the beginning of the file and ofcourse do not forget to derive the map from it and use pointer to interface. combat class will see the interface and pure virtual function, so it will be okay.
I see this problem when I want to use single page online compiler
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class MapIf {
public:
virtual void relaypointa() = 0;
};
class Player {
public:
int health;
int damage;
int defense;
int gems = 0;
string race;
string name;
string location;
};
class Enemy {
public:
int ehealth;
int edamage;
int edefense;
int echoice;
};
class combat {
public:
MapIf * mapobj;
int damagedealt;
Player playerobj;
Enemy enemeyobj;
string cchoice;
string retry;
void initial() {
cout << "A wild orc has appeared\n";
cout << "What do you do?\n";
cout << "---------------------------\n";
cout << "|-------------------------|\n";
cout << "|----Attack-----Defend----|\n";
cout << "|-------------------------|\n";
cout << "---------------------------\n";
cin >> cchoice;
this -> battle();
}
void newturn() {
cout << "The orc is still alive!";
cout << "What do you do?";
cout << "\n---------------------------\n";
cout << "|-------------------------|\n";
cout << "|----Attack-----Defend----|\n";
cout << "|-------------------------|\n";
cout << "---------------------------\n";
cin >> cchoice;
this -> battle();
};
void battle() {
enemeyobj.echoice = rand() % 2;
if (enemeyobj.echoice = 1) {
if (cchoice == "Attack") {
playerobj.damage;
enemeyobj.ehealth = enemeyobj.ehealth - playerobj.damage;
cout << "You did " << playerobj.damage << " points of damge to the enemey.\n";
if (enemeyobj.ehealth > 0) {
playerobj.health = enemeyobj.edamage - playerobj.health;
cout << "The enemyattacked you. You now have " << playerobj.health << " health";
if (playerobj.health > 0) {
this -> newturn();
} else if (playerobj.health <= 0) {
cout << playerobj.name << "was killed\n";
cout << "Game Over";
}
} else if (enemeyobj.ehealth <= 0) {
cout << "You have defeated the orc!";
if (playerobj.location == "a") {
mapobj -> relaypointa();
}
}
} else if (cchoice == "Defend") {
damagedealt = enemeyobj.edamage - playerobj.defense;
playerobj.health = damagedealt - playerobj.health;
cout << "You defend but the enemey was able to deal\n";
cout << damagedealt << " points of damage your health is\n";
cout << playerobj.health;
if (playerobj.health > 0) {
this -> newturn();
} else if (playerobj.health <= 0) {
cout << playerobj.name << "was killed\n";
cout << "Game Over";
}
}
} else if (enemeyobj.echoice = 2) {
if (cchoice == "Attack") {
damagedealt = enemeyobj.edefense - playerobj.damage;
enemeyobj.ehealth = enemeyobj.ehealth - damagedealt;
cout << "You did " << damagedealt << " points of damage to the enemey";
if (enemeyobj.ehealth > 0) {
this -> newturn();
} else if (enemeyobj.ehealth <= 0) {
cout << "You have defeated the orc!";
mapobj -> relaypointa();
}
} else if (cchoice == "Defend") {
cout << "Both parties defended";
this -> newturn();
}
}
}
};
class Map: public MapIf {
public: combat combatobj;
string mchoice;
int espawn;
Player playerobj;
Enemy enemeyobj;
void relaypointaespawn() {
playerobj.location == "relaypointa";
enemeyobj.ehealth = rand() % 50 + 100;
enemeyobj.edamage = rand() % 50 + 75;
enemeyobj.edefense = rand() % 50 + 50;
combatobj.initial();
}
void relaypointa() {
cout << "You have found yourself at the\n";
cout << "mouth of a mighty river to the north\n";
cout << "What do you want to do?\n";
}
void relaypointb() {
playerobj.location == "relaypointb";
cout << "\n\n%%%%%%%%%%%%%%%%%%%%\n";
cout << "% %\n";
cout << "% #Wild North# %\n";
cout << "% %\n";
cout << "%%%%%%%%%%%%%%%%%%%%\n\n";
cout << "You have entered the wild north this is where your journey starts\n";
cout << "What would you like to do\n\n";
cin >> mchoice;
if (mchoice == "Travel") {
cout << "Where would you like to travel?\n";
cin >> mchoice;
if (mchoice == "North") {
} else if (mchoice == "East") {
} else if (mchoice == "South") {
} else if (mchoice == "West") {
this -> relaypointaespawn();
} else {
cout << "Invalid command\n\n";
this -> relaypointb();
}
}
}
void relaypointcespawn() {
playerobj.location == "a";
enemeyobj.ehealth = rand() % 50 + 100;
enemeyobj.edamage = rand() % 50 + 75;
enemeyobj.edefense = rand() % 50 + 50;
espawn = rand() % 2;
}
};
int main() {
}