Getting large negative numbers printing arrays - c++

Hello Im getting negative valhes when trying to output some variables to the screen.
Ive looked this up and in most cases its an uninitialized variable but I cant find anything wrong.
Saying I have too much code to text ratio but I really dont know how to reiterate so heres some filler.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int Input;
int WepType;
string Weapon;
string WeaponType;
int Stats[3];
int AtkStats[4];
cout << "Pick your weapon.\n" << endl;
cout << "{===================================================}\n";
cout << "[ ]\n";
cout << "[ Iron Longsword Sharp Fishing Spear ]\n";
cout << "[ 1 ]\n";
cout << "[ ]\n";
cout << "[ Ornate Hunting Bow ]\n";
cout << "[ ]\n";
cout << "{===================================================}\n";
//Weapon Selection
cin >> Input;
if(Input == 1)
{
WepType = 1;
Weapon = "Iron Longsword";
WeaponType = "OneHanded";
Stats[0] = Stats[0] + 10;
Stats[1] = Stats[1] + 0;
Stats[2] = Stats[2] + 0;
AtkStats[0] = AtkStats[0] + 10;
AtkStats[1] = AtkStats[1] + 0;
AtkStats[2] = AtkStats[2] + 0;
AtkStats[3] = AtkStats[3] + 0;
cout << "Weapon = " << Weapon << endl;
cout << "Weapon Type = " << WeaponType << endl;
cout << "Health = " << Stats[0] << endl;
cout << "Physical = " << AtkStats[0] << endl;
cout << "Light = " << AtkStats[1] << endl;
cout << "Dark = " << AtkStats[2] << endl;
cout << "Temporal = " << AtkStats[3] << endl;
}
return 0;
}

The problem is here:
int Stats[3];
int AtkStats[4];
You should do:
int Stats[3] = {0, 0, 0};
int AtkStats[4] = {0, 0, 0, 0};
Or as BlastFurnace pointed out in the comments (which I forgot about):
int Stats[3] = {}; // Initialize all elements to zero.
int AtkStats[4] = {};
In order to initialize the values. Right now they are just random junk, so when you assign, you get errors.

Related

Basic program for calculating money [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I have a basic assignment and can't get the program right. The assignment is to make a program that displays the minimum amount of banknotes and coins necessary to pay.
#include <iostream>
using namespace std;
int main()
{
int pari;
cin >> pari;
switch (pari)
{
case 1: cout << pari/5000 << "*5000" << endl;
break;
case 2: cout << pari/1000 << "*1000" << endl;
break;
case 3: cout << pari/500 << "*500" << endl;
break;
case 4: cout << pari/100 << "*100" << endl;
break;
case 5: cout << pari/50 << "*50" << endl;
break;
case 6: cout << pari/10 << "*10" << endl;
break;
case 7: cout << pari/5 << "*5" << endl;
break;
case 8: cout << pari/2 << "*2" << endl;
break;
case 9: cout << pari/1 << "*1" << endl;
break;
default: cout << "WRONG";
}
return 0;
}
For example:
Input:
54321
Output:
10x5000
4x1000
0x500
3x100
0x50
2x10
0x5
0x2
1x1
I tried with switch case, with if statements, but nothing works.
To get the kind of output you have shown, use logic that looks more like this instead:
#include <iostream>
using namespace std;
int main()
{
int pari;
cin >> pari;
cout << pari/5000 << "*5000" << endl;
pari %= 5000;
cout << pari/1000 << "*1000" << endl;
pari %= 1000;
cout << pari/500 << "*500" << endl;
pari %= 500;
cout << pari/100 << "*100" << endl;
pari %= 100;
cout << pari/50 << "*50" << endl;
pari %= 50;
cout << pari/10 << "*10" << endl;
pari %= 10;
cout << pari/5 << "*5" << endl;
pari %= 5;
cout << pari/2 << "*2" << endl;
pari %= 2;
cout << pari/1 << "*1" << endl;
return 0;
}
Online Demo
Which can be simplified if you put the banknotes in an array and loop through it, eg:
#include <iostream>
using namespace std;
int main()
{
const int bankNotes[] = {5000, 1000, 500, 100, 50, 10, 5, 2, 1};
const int numBankNotes = sizeof(bankNotes)/sizeof(bankNotes[0]);
int pari;
cin >> pari;
for (int i = 0; i < numBankNotes; ++i) {
cout << pari/bankNotes[i] << "*" << bankNotes[i] << endl;
pari %= bankNotes[i];
}
return 0;
}
Online Demo
I have written several versions for you here.
Hopefully it will help you to understand the procedure.
Version 1
This is a navie version. This is how we would do it if we were doing it by hand.
int main()
{
int input_value = 0;
std::cin >> input_value; // First we get the input.
// We start with the highest value banknote.
int value = input_value;
int const number_of_5000_notes = value / 5000; // How many of these notes do
// we need?
value = value % 5000; // Now calculate the rest.
int const number_of_1000_notes = value / 1000; // How many of these notes do
// we need?
value = value % 1000; // Now calculate the rest.
int const number_of_500_notes = value / 500;
value = value % 500;
int const number_of_100_notes = value / 100;
value = value % 100;
int const number_of_50_notes = value / 50;
value = value % 50;
int const number_of_10_notes = value / 10;
value = value % 10;
int const number_of_5_notes = value / 5;
value = value % 5;
int const number_of_2_notes = value / 2;
value = value % 2;
int const number_of_1_notes = value;
// At the end we write the output
std::cout << "Input: " << input_value << std::endl;
std::cout << "Output:" << std::endl;
std::cout << number_of_5000_notes << " x 5000" << std::endl;
std::cout << number_of_1000_notes << " x 1000" << std::endl;
std::cout << number_of_500_notes << " x 500" << std::endl;
std::cout << number_of_100_notes << " x 100" << std::endl;
std::cout << number_of_50_notes << " x 50" << std::endl;
std::cout << number_of_10_notes << " x 10" << std::endl;
std::cout << number_of_5_notes << " x 5" << std::endl;
std::cout << number_of_2_notes << " x 2" << std::endl;
std::cout << number_of_1_notes << " x 1" << std::endl;
return 0;
}
Version 2
This is a more advanced version
int main()
{
int value = 0;
std::cin >> value; // Get input
// Check input
if (value == 0)
{
std::cout << "No value or 0 has been entered";
return 0;
}
// Output on the fly
std::cout << "Input: " << value << std::endl;
std::cout << "Output:" << std::endl;
// loop over a sorted list of banknotes.
for (auto note_value_ent : {5000, 1000, 500, 100, 50, 10, 5, 2, 1})
{
int const number_of_notes = value / note_value_ent;
value %= note_value_ent;
std::cout << number_of_notes << " x " << note_value_ent << std::endl;
}
return 0;
}
Both versions give the same result (except in the case of an invalid entry).

How to print data from a structure in a loop

I want a loop that prints the values for each soda.
When I try to print machine[j].name, an error is thrown stating that no operator is found or no acceptable conversion exists.
struct Soda
{
string name;
double price;
int quantity;
} a, b, c, d, e;
int main(int argc, char** argv)
{
Soda machine[5];
a.name = "Cola";
a.price = .80;
a.quantity = 20;
b.name = "Root Beer";
b.price = .75;
b.quantity = 20;
c.name = "Lemon-Lime";
c.price = .90;
c.quantity = 20;
d.name = "Grape - Mango";
d.price = .80;
d.quantity = 20;
e.name = "Cream";
e.price = .80;
e.quantity = 20;
cout << setw(5) << " Name" << setw(15) << " Cost"
<< setw(15) << " Stock" << setw(14) << "";
for (int i = 0; i < 5; i++)
for (int j = 0; j < 3; j++){
cout << left << setw(5) << machine[j].name
<< setw(15) << " Cost" << setw(15) << " Stock"
<< setw(14);
return 0;
}
It appears that you are mixing up the array with the declaration for separate variables. You have set values on the non-array variables and then you are trying to loop through the array.
Instead, you should set the values on the actual elements of the array.
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
struct Soda
{
string name;
double price;
int quantity;
};
int main(){
Soda machine[5];
machine[0].name = "Cola";
machine[0].price = .80;
machine[0].quantity = 20;
machine[1].name = "Root Beer";
machine[1].price = .75;
machine[1].quantity = 20;
machine[2].name = "Lemon-Lime";
machine[2].price = .90;
machine[2].quantity = 20;
machine[3].name = "Grape - Mango";
machine[3].price = .80;
machine[3].quantity = 20;
machine[4].name = "Cream";
machine[4].price = .80;
machine[4].quantity = 20;
cout << "Name Cost Stock" << endl;
for (int i = 0; i < 5; i++)
cout << machine[i].name << " " << machine[i].price << " " << machine[i].quantity << endl;
}
You are trying to print out the contents of objects (array of objects ) machine[i], when instead you have assigned values to some different objects: a, b, c, d, e.
Solution:
1. Either print a.name, b.name etc.
2. or instead of
a.name = "Cola";
a.price = .80;
write:
machine[i].name = "Cola";
machine[i].price = .80;
Since you marked this as C++, I suggest you try a vector (for machine).
int main()
{
vector<Soda> machine;
Soda tmpSoda;
{
tmpSoda.name = "Cola";
tmpSoda.price = .80;
tmpSoda.quantity = 20;
machine.push_back(tmpSoda);
}
{
tmpSoda.name = "Root Beer";
tmpSoda.price = .75;
tmpSoda.quantity = 20;
machine.push_back(tmpSoda);
}
// ....
{
tmpSoda.name = "Cream";
tmpSoda.price = .80;
tmpSoda.quantity = 20;
machine.push_back(tmpSoda);
}
Now all soda's are in the vector (named machine), so you can now report each element in a loop.
cout << "Name Cost Stock" << endl;
for (int i=0; i<machine.size(); ++i)
{
cout << machine[i].name << " "
<< machine[i].price << " "
<< machine[i].quantity << endl;
}
Since you marked this as C++, I suggest you try a vector of class instances. Note how the ctor fills in the values of each Soda, and the "show" method uses the private data attributes of each instance.
class Soda
{
public:
Soda(std::string aName,
double aPrice,
int aQuantity) :
name(aName),
price(aPrice),
quantity(aQuantity)
{
}
~Soda() {
name.erase();
quantity = 0;
}
std::string show() {
std::stringstream ss;
ss << std::right << std::setw(14) << name << " "
<< std::left << std::setw(8) << price << " "
<< std::setw(7) << quantity;
return (ss.str());
}
static std::string showHdr() {
std::stringstream ss;
ss << std::right << std::setw(14) << "Name" << " "
<< std::left << std::setw(8) << "Price" << " "
<< std::left << std::setw(7) << "Stock";
return (ss.str());
}
private:
std::string name;
double price;
int quantity;
};
Main now reduces to:
std::vector<Soda> machine;
// load the machine with soda's
machine.push_back(Soda("Cola", .80, 20));
machine.push_back(Soda("Root Beer", .75, 20));
machine.push_back(Soda("Lemon-Lime", .90, 20));
machine.push_back(Soda("Grape - Mango", .80, 20));
machine.push_back(Soda("Cream", .80, 20));
// show machine inventory
{
// hdr
std::cout << Soda::showHdr() << std::endl;
for (auto i : machine)
std::cout << i.show() << std::endl;
}

Newbie in C++. First text game

I study C ++ and try to create the first game. Here's the code:
#include <iostream>
#include <string>
using namespace std;
void info () {
int LVL = 1;
int money = 1000;
int EXP = 0;
int work = 200;
int learn = 15;
int k = 0;
}
void menu ()
{
info ();
char menu_items;
cout << "Choose action: " << "\n" << "1. Work" << "\n" << "2. Learn" << endl;
cin >> k;
if (k == 1){
int money = money + work;
cout << "U worked (+ "<< money << " dollars)" << "\n" << endl;
} if (k == 2) {
int EXP = EXP + learn;
cout << "U learned (+ " << EXP << " EXP)" << "\n" << endl;
} else {
cout << "ERROR" << endl;
}
}
int main()
{
info ();
while (LVL == 10) {
cout << "End game!";
}
while (LVL != 10) {
cout << "Your data: " << "\n" << "Money: " << money << "\n" << "EXP: " << EXP << "\n" << "LVL: " << LVL << "\n" << endl;
menu ();
}
}
Please correct the following:
1) The cyclic output data after rewrite
2) Proper cycle add money and experience when choosing one of the following actions
Info should probably be a class or struct. You only want to instantiate it once, and persist the values over your calls.
One option might be:
#include <iostream>
#include <string>
using namespace std;
struct info {
int lvl = 1;
int money = 1000;
int exp = 0;
const int work = 200;
const int learn = 15;
};
int main()
{
info i;
string k;
while (i.lvl < 10)
{
cout << "Your data: " << "\n" << "Money: " << i.money << "\n" << "EXP: " << i.exp << "\n" << "LVL: " << i.lvl << endl;
cout << "Choose action: " << "\n" << "1. Work" << "\n" << "2. Learn" << endl;
cin >> k;
if (k == "1")
{
i.money += i.work;
cout << "You worked (+ " << i.work << " dollars, now " << i.money << ")" << endl;
}
else if (k == "2")
{
i.exp += i.learn;
cout << "You learned (+ " << i.learn << " EXP, now " << i.exp << ")" << endl;
}
else
{
cout << "ERROR" << endl;
}
}
cout << "You won!" << endl;
}
#include <iostream>
#include <string>
using namespace std;
void menu()
{
int money = 1000;
int EXP = 0;
int work = 200;
int learn = 15;
int k = 0;
cout << "Choose action: \n 1. Work \n 2. Learn "<< endl;
cin >> k;
if (k == 1){
money =money + work;
cout << "U worked (+ " << money << " dollars)" << "\n" << endl;
} if (k == 2) {
EXP = EXP + learn;
cout << "U learned (+ " << EXP << " EXP)" << "\n" << endl;
}
else {
cout << "ERROR" << endl;
}
}
int main()
{
int money = 1000;
int LVL = 1;
int EXP = 0;
while (LVL == 10) {
`cout << "End game!"; `
}
while (LVL != 10) {
cout << "Your data: " << "\n" << "Money: " << money << "\n" << "EXP: " << EXP << "\n" << "LVL: " << LVL << "\n" << endl;
menu();
}
return 0;
}

Comapring two vector elements and get EXC_BAD_ACCESS(code=1, address = 0x0) error

I am writing a program that needs to compare two elements at a time (of a 9 element vector) to find the lowest element. To do this I created a Sort function that acts like a Bubblesort and at the end of the sort I will take the first element of the vector (Which will be the lowest). My problem is that Xcode is telling me my equation is pointing to NULL. Any ideas?
void ParkingLot::GateA(){
vector<int> AvailSpots (9);
AvailSpots[0] = 40;
AvailSpots[1] = 20;
AvailSpots[2] = 50;
AvailSpots[3] = 30;
AvailSpots[4] = 55;
AvailSpots[5] = 15;
AvailSpots[6] = 20;
AvailSpots[7] = 33;
AvailSpots[8] = 27;
vector<string> Lot (9);
Lot[0] = "A";
Lot[1] = "B";
Lot[2] = "C";
Lot[3] = "D";
Lot[4] = "E";
Lot[5] = "F";
Lot[6] = "G";
Lot[7] = "H";
Lot[8] = "I";
vector<int> Cost (9);
Cost[0] = 25.00;
Cost[1] = 22.50;
Cost[2] = 20.00;
Cost[3] = 22.50;
Cost[4] = 20.00;
Cost[5] = 17.50;
Cost[6] = 20.00;
Cost[7] = 17.50;
Cost[8] = 15.00;
vector<int> Distance (9);
Distance[0] = 10;
Distance[1] = 20;
Distance[2] = 30;
Distance[3] = 20;
Distance[4] = 30;
Distance[5] = 40;
Distance[6] = 30;
Distance[7] = 40;
Distance[8] = 50;
int choice2;
cout << "-------------------------------------------------------------------------" << endl;
cout << setw(50) << "GATE A: Lot Information" << endl;
cout << "-------------------------------------------------------------------------" << endl;
cout << "LOT ID : MAX CAPACITY : AVAILABLE SPOTS : COST($DD.CC) : DISTANCE" << endl;
cout << "-------------------------------------------------------------------------" << endl;
cout << Lot[0] << ": 40 : "<<AvailSpots[0]<<": "<<setw(20)<<" "<<Cost[0]<<" : " <<Distance[0] << endl;
cout << Lot[1] << ": 20 : "<<AvailSpots[1]<<": "<<setw(20)<<" "<<Cost[1]<<" : " <<Distance[1] << endl;
cout << Lot[2] << ": 50 : "<<AvailSpots[2]<<": "<<setw(20)<<" "<<Cost[2]<<" : " <<Distance[2] << endl;
cout << Lot[3] << ": 30 : "<<AvailSpots[3]<<": "<<setw(20)<<" "<<Cost[3]<<" : " <<Distance[3] << endl;
cout << Lot[4] << ": 55 : "<<AvailSpots[4]<<": "<<setw(20)<<" "<<Cost[4]<<" : " <<Distance[4] <<endl;
cout << Lot[5] << ": 15 : "<<AvailSpots[5]<<": "<<setw(20)<<" "<<Cost[5]<<" : " <<Distance[5] <<endl;
cout << Lot[6] << ": 20 : "<<AvailSpots[6]<<": "<<setw(20)<<" "<<Cost[6]<<" : " <<Distance[6] << endl;
cout << Lot[7] << ": 33 : "<<AvailSpots[7]<<": "<<setw(20)<<" "<<Cost[7]<<" : " <<Distance[7] << endl;
cout << Lot[8] << ": 27 : "<<AvailSpots[8]<<": "<<setw(20)<<" "<<Cost[8]<<" : " <<Distance[8] << endl;
cout << " Total : 290 : "<<TotalAvailSpots<<":" << endl;
cout << "Select a criteria to allot a parking lot :" << endl;
cout << "1. Based on Cost - Cheapest Parking Lot" << endl;
cout << "2. Based on Distance - Closest to Stadium" << endl;
cout << "0. EXIT" << endl;
cout << "Enter Option (1-2): " << endl;
cin >> choice2;
if (choice2 == 1) {
ParkingLot::Sort();
}
}
int ParkingLot::Sort(){
int cost;
for (int i = 0; i < 8; i++){
if (Cost[i] > Cost[i + 1]) { /////////////ERROR APPEARS HERE Thread1:EXC_BAD_ACCESS(code=1, address=(0x0)
ParkingLot::Swap(i, i+1);
}
}
cout << "Cost of parking lot " << Cost.front() << endl;
cin >> cost;
return cost;
}
void ParkingLot::Swap(int a, int b){
int tmp = Cost[a];
Cost[a] = Cost[b];
Cost[b] = tmp;
}
The variables you define in GateA are local to the function and hiding any member variables with the same names.
So the Cost vector you're using in Sort and Swap is empty because it is a different one from the one you built in GateA.
Remove the line
vector<int> Cost (9);
from GateA and instead call Cost.resize(9) before assigning the elements, or build the vector using push_back rather than direct indexing.

Lining columns up

Solved!
This is what I wrote:
cout << setw(4) << "Students";
cout << setw(20) << "Hours Worked";
cout << setw(20) << "of Total Hours";
cout << endl;
for (int i = 0; i < students; i++)
{
cout << setw(20);
cout << names[i];
cout << setw(10) << hours[i];
cout << setw(10) << percent[i];
cout << endl;
}
But if the first name is a few characters sorter or bigger than second name, they become misaligned. How would I keep each column aligned equally?
Try something like this:
#include<iostream>
#include <iomanip>
#include<string>
using namespace std;
int main()
{
int students = 5;
string names[5] = {"a","bccc","c","d","ecsdfsdfasdasasf"};
int hours[5] = {1,2,3,4,5};
int percent[5] = {10,20,30,40,54};
string column("Students");
int maxStringSize = 0;
int sizeOfStudentColumn = column.length();
for(int i = 0; i < 5; ++i)
{
if(maxStringSize < names[i].length())
maxStringSize = names[i].length();
}
if(sizeOfStudentColumn > maxStringSize)
maxStringSize = sizeOfStudentColumn;
cout<<"max size: "<<maxStringSize<<endl;
cout << setw(4) << "Students";
cout << setw(maxStringSize + 5) << "Hours Worked";
cout << setw(20) << "of Total Hours";
cout << endl;
for (int i = 0; i < students; i++)
{
// cout << setw(20);
cout << names[i];
int diff = maxStringSize - names[i].length();
cout << setw(diff + 5 ) << hours[i];
cout << setw(20) << percent[i];
cout << endl;
}
}