How do I change a char's values? - c++

I've created a program and it runs, however there are two problems. 1) Char doesn't change values as it should. 2) One of my total variables is stuck on one.
I've tested the code multiple times, and the char deptID is stuck on 'B'. I've tried going through the workflow and it's stuck on the value. Just to make sure, I wrote a cout line to check it throughout the workflow. Regardless of what I input, it's stuck on 'B'.
2) The variable TechTotal is seemingly stuck on 1. I've tested it using different values as well. I also went ahead and used a cout line to determine the value throughout the workflow to no success. I've made sure the variables are correct in calculating the variable. Both are correct.
Here's my main code:
int main(int argc, char** argv) {
welcomeScreen();
long int empID;
int TechAccAvg, TechTixAvg;
int BusTotal, TechTotal, BusAccAvg, BusTixAvg;
char deptID;
for (int i=0; i < 2; i++)
{
cout << "What department are you apart of?\n";
cin >> deptID;
if (deptID = 'B')
{
auto Averages = gatherData(deptID);
BusTixAvg = std::get<0>(Averages);
BusAccAvg = std::get<1>(Averages);
cout << BusTixAvg << endl;
cout << BusAccAvg << endl;
BusTotal = BusTixAvg + BusAccAvg;
cout << "Bus Total: " << BusTotal << endl;
}
else if (deptID = 'T')
{
auto TechAverages = gatherData(deptID);
TechTixAvg = std::get<0>(TechAverages);
TechAccAvg = std::get<1>(TechAverages);
cout << TechTixAvg << endl;
cout << TechAccAvg << endl;
TechTotal = TechTixAvg + TechAccAvg;
cout << "Tech Total: " << TechTotal << endl;
}
}
cout << "Tech: " << TechTotal << endl;
cout << "Business: " << BusTotal << endl;
summaryReport(TechTotal, BusTotal);
goodByeScreen();
return 0;
}```
` std::tuple<int, int> gatherData (char dept)
{
tuple <double, double> Averages;
int employeeNum=0, TotalTix=0, TotalAcc=0, trafficTickets=0, accidents=0;
long int empID=0;
double TixAverage=0, AccAverage=0;
char deptID;
cout << dept << endl;
cout << "How many employees do you have?\n";
cin >> employeeNum;
for(int j = 0; j < employeeNum; j++)
{
cout << "Please enter your employees ID number\n";
cin >> empID;
cout << "How many tickets did they have this year?\n";
cin >> trafficTickets;
TotalTix += trafficTickets;
cout << "How many accidents did they have this year?\n";
cin >> accidents;
TotalAcc += accidents;
}
TixAverage = TotalTix / employeeNum;
AccAverage = TotalAcc / employeeNum;
cout << "Department: " << dept << endl;
cout << "Total employees: " << employeeNum << endl;
cout << "Total tickets: " << TotalTix << endl;
cout << "Total Accidents: " << TotalAcc << endl;
Averages = make_tuple (TotalTix, TotalAcc);
return Averages;
}```
This is used to create the tuple that is used in determining Totals for both 'B' and 'T' depts.
Fixing both the char dept and the TechTotal would fix the entire program, I think. Those are the only things holding the program back. I've been stuck on this problem for a few hours now and I'm kind of lost as to why it's not changing those values. Any help would be appreciated, thank you in advance!

Solution
Replace else if (deptID = 'T') with else if (deptID == 'T') and if (deptID = 'B') with if (deptID == 'B').
Explanation
The single equal sign = means assignment. Therefore, everytime the program runs, deptID will be assigned to B and the statement will return true, satisfying the if statement.
However, you want to compare two values to see if they are equal. Therefore, you must use == (equality).
Because the statements in the else if will never execute, TechTotal will remain uninitialised, and the value in that memory address just so happens to be 1.

Related

Looping Confusion

My code seems to ask twice instead of once if I want to run the code again. I just want it to run normally like my other cases which only ask once after I have viewed the activity and these two activities are the only ones with problems. What seems to be the problem here:
case 5:
cout<<"Here are the list of activities in Activity 5:" << endl;
cout<<"[5.1]Determining a Number within the Array" << endl;
cout<<"[5.2]Determining the Highest and Lowest integer" << endl;
cout<<"[5.3]Reversed Array" << endl;
cin >> choice;
system("CLS");
if(choice == 5.1){
counter +=1;
int nos[10];
int det;
cout <<"Note: Do not input any decimal numbers." << endl;
for(int array = 1; array < 11; array++){
cout << "Input integers 1-10 only. [" << array << "]";
cin >> nos[det];
}
cout << "Type in 1 integer value only.[" << det << "]";
cin >> det;
if(det >= nos[1] || det <= nos[10]){
cout << "The value is within the scope of the array.";
}
else{
cout << "The value is not within the scope of the array.";
}
system ("PAUSE");
system ("CLS");
cout << "Do you want to run the program again? (y/n)" << endl;
cin >> choose;
}
else if(choice == 5.2){
counter +=1;
cout <<"Note: Do not input any decimal numbers." << endl;
cout <<"Enter your integers." << endl;
int nos[10];
int put;
for(int rep = 1; rep < 11; rep++){
cout <<"[" << rep << "]";
cin >> nos[rep];
}
int highnos = nos[1];
int lownos = nos[1];
for(int rep = 1; rep < 11; rep++){
if(nos[rep] > highnos){
highnos = nos[rep];
}
}
cout << "Your highest integer is:" << highnos << endl;
for(int rep = 1; rep > 11; rep++){
if(nos[rep] < lownos){
lownos = nos[rep];
}
}
cout <<"Your lowest integer is:"<< lownos << endl;
system ("PAUSE");
system ("CLS");
cout << "Do you want to run the program again? (y/n)" << endl;
cin >> choose;
}
P.S. my activities also has errors but dont mind it :D
First of all, you haven't initialized anything so everything is taking garbage values.
initialize det first and if you want to input the whole array then run a loop. cin>>nos[det] only inputs one value at a garbage index according to your code.
This code is a mess. Kindly fix initializations and inputs, then share the output you're getting vs the output you want.

C++ array structures

I was reading the chapter on structures in my book, and it got me re-modifying a program I already made, but this time using structures which I have never used before; however, after finishing the program, there's one issue I'm not understanding. The output of the program only displays once. It's in a for loop, and yet even though it asks me to input my information three times, it only outputs the first information.
I'm probably just not understanding how arrays in structures work.
An example of my issue is the following.
I have my output on the following loop
for(int counter = 0; counter <size; counter++)
The size is 3, which would mean I'll get the output printed three times; however the answer I'm getting is the same as if I was asking for the following.
Listofnames[0].F_name
When what I actually want is
Listofnames[0].F_name Listofnames[1].F_name Listofnames[2].F_name
However, I don't want to have to write it three times, I did to test it and it actually worked, but is that the only way to do it? Or did I miss something in my program?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Names
{
string F_name; //Creating structure called Names.
string L_name;
char Mi;
};
struct Payrate
{
double rate;
double hoursworked; //Creating structure called Payrate.
double gross;
double net;
};
int main()
{
double stateTax = 0, federalTax = 0, unionFees = 0, timeHalf = 1.5; //Initializing variables.
const int size = 2; //Array size.
Payrate employee[size]; //Structure variables
Names Listofnames[size];
for (int counter = 0; counter < size; counter++) //Initializing for loop.
{
cout << "What's your first name?: " << endl;
cin >> Listofnames[counter].F_name;
cout << "What's your last name?: " << endl; //Displaying names, and hours worked, rate.
cin >> Listofnames[counter].L_name;
cout << "What is your middle initial?: " << endl;
cin >> Listofnames[counter].Mi;
cout << "How many hours did you work? Please enter a number between 1-50: " << endl;
cin >> employee[counter].hoursworked;
cout << "What is your hourly rate? Please enter a number between 1-50: " << endl;
cin >> employee[counter].rate;
if (employee[counter].hoursworked < 0 || employee[counter].hoursworked >50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].rate < 0 || employee[counter].rate > 50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].hoursworked <= 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * employee[counter].rate; //Calculating gross.
}
else if (employee[counter].hoursworked > 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * (employee[counter].rate * timeHalf); //Calculating gross.
}
stateTax = employee[counter].gross * 0.06;
federalTax = employee[counter].gross * 0.12; //Calculates all the tax fees, and net.
unionFees = employee[counter].gross * 0.02;
employee[counter].net = employee[counter].gross - (stateTax + federalTax + unionFees);
}
cout << "FirstN " << "MI " << "LastName " << "\t" << "Rate " << "HoursWorked " << "TimeHalf " << "StateTax " << "FederalTax " << "UnionFees " << "Gross " << " " << "Net " << endl; //Displays header of output.
cout << "==================================================================================================================" << endl;
for (int counter = 0; counter <= size; counter++)
{
//Output.
cout << Listofnames[counter].F_name << "\t" << fixed << setprecision(2) << Listofnames[counter].Mi << " " << Listofnames[counter].L_name << "\t" << employee[counter].rate << "\t" << employee[counter].hoursworked << "\t" << setw(7) << timeHalf << "\t" << setw(8) << stateTax << setw(12) << federalTax << "\t" << unionFees << "\t" << employee[counter].gross << "\t" << employee[counter].net << endl;
system("pause");
}
}
P.s If you had to re modify this program again, what would you use to simplify it. Asking so I can keep re-modifying, and learn more advanced stuff. Vectors, pointers? Thanks in advance.
You have an array with 3 indexes but your loop is only going upto 2 indexes. Change your for loop to this.
for (int counter = 0; counter <= size; counter++)
Now, this loop will print the all the indexes.
Instead of using a static value you can also use this.
for (int counter = 0; counter < sizeof(Listofnames)/sizeof(Listofnames[0]); counter++)
sizeof(Listofnames)/sizeof(Listofnames[0]) This will give you the total size of your array.
Ideone Link

How do you make a counter to count the number of even and odd numbers entered by user?

I have this code so far that is supposed to keep asking the user for a number until they type 0. Then the program will tell the user how many odds and evens they typed. I cannot get the latter function to work correctly. Any tips? I am a beginner, so please no advanced ways to solve this :D
#include <iostream>
using namespace std;
int main ()
{
int n;
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
return 0;
}
A couple things:
Code indentation (or lack thereof) makes this really hard to read. Indentation is not only cosmetic, but can help in understanding code.
You are setting the counter variables to zero each time the loop runs. Declare them outside of the loop so they retain their values.
The else clause of the if statement has erroneous syntax. Use a simple else instead, as there are only two cases for the parity of n.
When the user types 0 to exit the loop, it too is counted as an even integer. Add a condition in the if statement to account for this.
Applying these changes yields this code:
int n;
int myCounter1 = 0, myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do {
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0 && n != 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
} while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
This
else n == 0
{
myCounter2++;
}
should be
else
{
myCounter2++;
}
Honestly, I don't even know why it didn't grab your attention, since it can't compile.
Also, you shouldn't set the counters to zero in the loop. So
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
should be
int myCounter1=0, myCounter2=0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
And, finally, since you probably shouldn't count the 0 as one of the integers entered...
cout << "You entered " << myCounter1-1 << " even numbers, and " << myCounter2 << " odd numbers " << endl;
You have 2 bugs and 1 syntax error.
line:else n == 0 should be simply else
The 2 bugs are related to your counters:
1) You have to exclude the 0 input from the counters.
2) Every time you are reading a number your are setting them (the counters) to zero, which means that you will always ending with zero and one.
Here it is for anyone interested:
include
using namespace std;
int main ()
{
int n;
int myCounter1 = 0;
int myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter2 << " odd numbers, and " << myCounter1-1 << " even numbers " << endl;
return 0;
}

How do I display a list of previous guesses before a user guesses a new number, using an array?

I am creating a guessing game. I need to display the users' previous guesses every time the user makes another guess. I am using an array and pointers. The code below only displays the most recent thing entered by the user. I need it to display a list of previous inputs. The part of the code that includes the pointer seems to be where my issue is located, but I don't know exactly where?
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
void arrayTable(int[]);
int reviewGuess(int Answer, int userGuess);
int _tmain(int argc, _TCHAR* argv[])
{
int guessNum = 3; // Declares how many guesses the user can take.
int userGuess = 0;
int Answer;
char Choice;
int *pointer = NULL;
srand(time(NULL));
Answer = rand() % 20 + 1; //Gives a random number ranging from 1 to 20
do{
int x;
cout << " ____________________________________________________\n";
cout << " | |\n";
cout << " | I want to play a game |\n"; // Displays a welcome message
cout << " | I am thinking of a number between 1 through 20. |\n";
cout << " | Can you guess the number in less than " << guessNum << " tries ? |\n";
cout << " | Press '1' to play. |\n";
cout << " | Press '2' if you want to EXIT!!! |\n";
cout << " |__________________________________________________|\n";
cin >> x;
switch (x)
{
case 1:
for (int i = 0; i < guessNum; i++) //Counter, for loop, stops when condition is met.
{
cout << " This is guess# " << i + 1 << " : "; //Takes the user input
cin >> userGuess;
int guessNum = 1;
pointer = new int[guessNum];
for (int i = 0; i < guessNum; i++) //Store the user guesses
{
*(pointer + i) = userGuess;
}
cout << "Here is a list of your guesses" << endl;
for (int i = 0; i < guessNum; i++) // Display the user guesses.
{
cout << " Guess# " << i + 1 << " is " << *(pointer + i) << endl;
}
reviewGuess(Answer, userGuess); //Calls the function
}
cout << " ------------------> <----------------------\n";
cout << " ------------------> You Lost!!! <----------------------\n";
cout << " ------------------> <----------------------\n";
cout << " You have exceeded the amount of guesses you were given.\n";
cout << " The correct Answer is : " << Answer << endl;
break;
case 2:
cout << "-------------->Thank You.\n";
cout << "-------------->Have a good day.\n";
break;
system("pause");
return 0;
}
cout << "would you like to play again (y/n)?";
cin >> Choice;
} while (Choice == 'y');
system("pause");
return 0;
}
int reviewGuess(int Answer, int userGuess)
{
if (userGuess != Answer)
{
if (userGuess > Answer)
cout << " -----> 1 \n";
else
cout << " -----> -1 \n";
}
else
{
cout << " -----> 0 \n";
cout << " Good JOb, you have guessed the right number. \n";
system("pause");
return 0;
}
}
review the changes, and don't just copy and paste.
to access pointer array members, you can use the index [].
you are already in a for loop, so you dont want to create another for loop getting input, that would be 3 x 3 requests for data.
you were storing the data into an int, not into the array you created with pointer.
pointer isn't a very good name, when its an array of guesses. try calling it something more readable.
once it ran, if the user won, it still triggered losing code. you need to break out before accessing that code the way you have it set up. i created a bool, and changed your reviewguess method to return a bool whether they won or not. break out on exiting. note the double use of breaks; its in a for loop in a switch. you have to break out of the foor loop, and then break out of the switch. you cannot just put it after the for loop, as it will then keep asking for input if they win, and then report they won at the end.
note the use of the global constant to keep track of how many guesses. you were declaring and initializing the same variables all over the place. initialize with the type keyword once, at the start, and if you need the variable in the loop, initalize it before the loop so you dont try to reinitialize every iteration.
logic was reversed as far as higher or lower with reviewGuess
Not a bad start, keep your head up, and i hope i could help you out!
this is my first time answering a question.
Code:
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
void arrayTable(int[]);
bool reviewGuess(int, int);
int _tmain(int argc, _TCHAR* argv[])
{
const int MAX_NUMBER_GUESSES = 3;// Declares how many guesses the user can take.
int currentGuessNum = 0;
int userGuess = 1;
int Answer;
char Choice;
int x;
int *arrGuesses = NULL;
bool gameWon = false;
srand(time(NULL));
//Gives a random number ranging from 1 to 20
do {
Answer = rand() % 20 + 1; //Gives a random number ranging from 1 to 20
//you want this in the loop otherwise you always have same answer
cout << " ____________________________________________________\n";
cout << " | |\n";
cout << " | I want to play a game |\n"; // Displays a welcome message
cout << " | I am thinking of a number between 1 through 20. |\n";
cout << " | Can you guess the number in less than " << MAX_NUMBER_GUESSES << " tries ? |\n";
cout << " | Press '1' to play. |\n";
cout << " | Press '2' if you want to EXIT!!! |\n";
cout << " |__________________________________________________|\n";
cin >> x;
switch (x)
{
case 1:
userGuess = 1;
arrGuesses = new int[MAX_NUMBER_GUESSES];
for (int i = 0; i < MAX_NUMBER_GUESSES; i++) //Counter, for loop, stops when condition is met.
{
cout << " This is guess# " << userGuess << " : " << endl; //Takes the user input
cin >> arrGuesses[i];
cout << "Here is a list of your guesses" << endl;
for (int i = 0; i < userGuess; i++) // Display the user guesses.
{
cout << " Guess# " << i+1 << " is " << arrGuesses[i] << endl;
}
gameWon = reviewGuess(Answer, arrGuesses[i]); //Calls the function
if (gameWon)
{
break;
}
userGuess++;
}
if (gameWon)
{
break;
}
cout << " ------------------> <----------------------\n";
cout << " ------------------> You Lost!!! <----------------------\n";
cout << " ------------------> <----------------------\n";
cout << " You have exceeded the amount of guesses you were given.\n";
cout << " The correct Answer is : " << Answer << endl;
break;
case 2:
cout << "-------------->Thank You.\n";
cout << "-------------->Have a good day.\n";
break;
system("pause");
return 0;
}
cout << "would you like to play again (y/n)?";
cin >> Choice;
} while (Choice == 'y');
system("pause");
return 0;
}
bool reviewGuess(int Answer, int userGuess)
{
if (userGuess != Answer)
{
if (userGuess < Answer)
cout << " -----> 1 \n";
else
cout << " -1 <----- \n";
return false;
}
else
{
cout << " -----> 0 \n";
cout << " Good JOb, you have guessed the right number. \n";
system("pause");
return true;
}
}

Creating and clearing an array of structures

I've been trying to write a short program allowing the user to add entries to a "database", listing the entries they have put in, and the ability to clear all the entries without ending the program. Here's what i've got
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
struct BIRTH
{int month; int year;};
struct ID
{string name; bool vip; float score;
struct BIRTH date;} ;
int main(int argc, char** argv) {
ID **ptrarr;
ptrarr = new ID * [10];
for (int r=0; r<10; r++)
{ptrarr[r] = new ID[1] ;}
int counter = 0;
while(counter<100){
cout << "Type add to create a new entry" << endl;
cout << "Type list to see all entries" << endl;
cout << "Type clear to delete all entries" << endl;
cout << "Type exit to terminate" << endl;
string command = "0";
getline (cin,command);
if(command=="add")
{
cout << "Enter name" << endl;
getline (cin,ptrarr[counter][1].name);
cout << "VIP? 1 for yes, 0 for no" << endl;
cin >> ptrarr[counter][1].vip;
cout << "Enter score" << endl;
cin >> ptrarr[counter][1].score;
cout << "Month of birth" << endl;
cin >> ptrarr[counter][1].date.month;
cout << "Year of birth" << endl;
cin >> ptrarr[counter][1].date.year;
counter++;
}
else if(command=="list")
{
for (int i=0; i<counter; i++)
{int n=i+1;
cout << n << " "
<< ptrarr[i][1].name << " ";
if (ptrarr[i][1].vip)
{cout << "VIP ";}
cout << "Score: " << ptrarr[i][1].score << " "
<< "Born: " << ptrarr[i][1].date.month << "/" << ptrarr[i][1].date.year << endl;
}
}
else if(command=="clear")
{delete[] ptrarr;
cout << "Entries cleared" << endl;}
else if(command=="exit")
{return 0;}
else
cout << "try again" << endl;
}
return 0;
}
Now here's the deal: the following code successfully compiles, but when I type in the "add" command, the program crashes (achievement unlocked, didn't think it's possible to obtain with such a short code). The most important thing is that the array is made of a multitype structure and that the "clear" command wipes out all the entries in the array.
NOTE: I understand that there are thousand better ways to write this piece of code, but I'm writing it to practice the things I have covered so far regarding C++. So unless it is absolutely necessary for the code to run, please do not introduce any new gimmicks =)
Replace all ptrarr[counter][1] with ptrarr[counter][0] fixes the problem.
Further advices:
I. This code has redundancy:
ID **ptrarr;
ptrarr = new ID * [10];
for (int r=0; r<10; r++)
{ptrarr[r] = new ID[1] ;}
Replace it with:
ID *ptrarr;
ptrarr = new ID [10];
Then you do not need extra [0] at the end of each ptrarr[counter]
II. functions make your code more readable:
if(command=="add")
add();
else if(command=="list")
list();
else if(command=="clear")
clear();
else if(command=="exit")
return 0;
else
cout << "try again" << endl;
Then decisions are made in a smaller area (Good practice for large programs.)
III. There is another mistake in your code:
else if(command=="clear")
{delete[] ptrarr;
cout << "Entries cleared" << endl;}
Here you should reset the counter. Also if you regard my point (I) this part is fine. Otherwise, if you use new with a for loop, I am afraid that you need to delete with a for loop too. Merely removing the root of the array tree brings you memory leak!
Also, if you cleared the list by delete, wont you need to store data in the list anymore? Using delete in linked lists is a good idea, but it does not apply here. Just reseting the counter does the job and it does not show IDs in the list anymore. The for inside the list does only count up to the counter.
If you exit the program don't you free the memory?
I say
delete [] ptrarr;
is good for being at exit.
You are creating an an array of pointers, each one of which points to one element:
ptrarr[r] = new ID[1] ;
The maximum index that you can use with ptrarr[r] is 0. Since you are using ptrarr[counter][1], you are accessing memory that is out of bounds. This leads to undefined behavior. Crashing is one such undefined behavior.
There are other issues with your code that you may want to fix.
More out of bounds memory access
You are using:
int counter = 0;
while(counter<100){
...
getline (cin,ptrarr[counter][1].name);
That is again going to lead to undefined behavior if counter > 10 since you allocated only 10 pointers for ptrarr.
Deleting the contents
You are using:
else if(command=="clear")
{
delete[] ptrarr;
cout << "Entries cleared" << endl;
}
There are couple of problems with this:
You have memory leak. You never call delete [] on what ptrarr[0] - ptrarr[9] point to. You'll have to use:
else if(command=="clear")
{
for ( int i = 0; i < 10; ++i )
{
delete [] ptrarr[i];
}
delete[] ptrarr;
cout << "Entries cleared" << endl;
}
Remember that every allocation must have a corresponding deallocation. Otherwise, you are leaking memory.
Once you call delete [] ptrarr;, it points to dangling memory. I don't see any code that reallocates memory for ptrarr while you continue to use it.
You need to reallocate memory and reset counter to 0 when the user chooses "clear".
My suggestion
You don't two levels of pointers. You just need something like:
int const MAX_ITEMS = 100;
ID* IDarr = new ID[MAX_ITEMS];
Instead of ptrarr[counter][1], use IDarr[counter].
Use MAX_ITEMS in the expression of the while statement instead of the magic number 100.
int counter = 0;
while(counter<MAX_ITEMS){
When processing "clear", you don't need to deallocate or allocate memory. Just reset counter.
else if(command=="clear")
{
counter = 0;
cout << "Entries cleared" << endl;
}
Make sure to deallocate memory before returning from main.
Here's the complete main function with the changes:
int main(int argc, char** argv) {
const int MAX_ITEMS = 100;
ID* IDarr = new ID[MAX_ITEMS];
int counter = 0;
while(counter < MAX_ITEMS){
cout << "Type add to create a new entry" << endl;
cout << "Type list to see all entries" << endl;
cout << "Type clear to delete all entries" << endl;
cout << "Type exit to terminate" << endl;
string command = "0";
getline (cin,command);
if(command=="add")
{
cout << "Enter name" << endl;
getline (cin, IDarr[counter].name);
cout << "VIP? 1 for yes, 0 for no" << endl;
cin >> IDarr[counter].vip;
cout << "Enter score" << endl;
cin >> IDarr[counter].score;
cout << "Month of birth" << endl;
cin >> IDarr[counter].date.month;
cout << "Year of birth" << endl;
cin >> IDarr[counter].date.year;
counter++;
}
else if(command=="list")
{
for (int i=0; i<counter; i++)
{
int n=i+1;
cout << n << " " << IDarr[i].name << " ";
if (IDarr[i].vip)
{
cout << "VIP ";
}
cout
<< "Score: " << IDarr[i].score << " "
<< "Born: " << IDarr[i].date.month << "/" << IDarr[i].date.year << endl;
}
}
else if(command=="clear")
{
counter = 0;
cout << "Entries cleared" << endl;
}
else if(command=="exit")
{
// Don't use return 0;
// Just break out of the while loop so that memory
// can be deallocated at the end of this function.
break;
}
else
cout << "try again" << endl;
}
delete [] IDarr;
return 0;
}
Array indices start at 0.
ptrarr[counter][1] refers to the second element of ptrarr[counter]. ptrarr[counter] points to an array of one element.
try this :
if(command=="add") {
cout << "Enter name" << endl;
getline (cin,ptrarr[counter][0].name);
cout << "VIP? 1 for yes, 0 for no" << endl;
cin >> ptrarr[counter][0].vip;
cout << "Enter score" << endl;
cin >> ptrarr[counter][0].score;
cout << "Month of birth" << endl;
cin >> ptrarr[counter][0].date.month;
cout << "Year of birth" << endl;
cin >> ptrarr[counter][0].date.year;
counter++;
}
else if(command=="list") {
for (int i=0; i<counter; i++){
int n=i+1;
cout << n << " "<< ptrarr[i][0].name << " ";
if (ptrarr[i][0].vip){
cout << "VIP ";
}
cout << "Score: " << ptrarr[i][0].score << " "
<< "Born: " << ptrarr[i][0].date.month << "/" << ptrarr[i][0].date.year << endl;
}
}
Conclusion :
Just as you initialized counter with 0 you should have used 0 index to access the first element;
Same goes while listing.
Arrays are 0 index based.