Changing a Second Value withing a Vector Object in C++ - c++

I'm quite new at C++, and am learning about vectors and all that fun stuff. I'm trying to figure out how I can have the user add a room on his selected floor. I have most of the problem done, but just that part I am having a hard time figuring out, any help would be appreciated! The main issue I think is at the function ReplaceFloor, but I have no idea how to make it in a way that the user selects Choice 4, then enters the floor that he wants a room to be added, and have that floor vector store one more room in it. Thank you for your help in advance! I tried to make it as best understandable as I could- sorry I'm quite new.
// Main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Floor.h" // must include Floor header file
#include "Room.h" // must include Room header file
#include "AccessPoint.h" // must include AccessPoint header file
#include <vector>
#include <string>
using namespace std;
// functions that fills up all Floors
void fillFloor(vector<Floor>&);
void deletesFloor(vector<Floor>&);
void replaceFloor(vector<Floor>&);
// functions that fills up all Rooms
void fillRoom(vector<Room>&);
void deletesRoom(vector<Room>&);
// functions that fills up all Access Points
void fillAccessPoint(vector<AccessPoint>&);
void printFloorVector(const vector<Floor>&); // prints the information of all floors
void printRoomVector(const vector<Room>&); // prints the information of all Rooms
void printAccessPointVector(const vector<AccessPoint>&); // prints the information of all Access Points
// Variable Declaration
int roomNumber;
int accessPointNumber;
int floorID =0;
int roomID = 0;
int accessPointID =0;
int floorTotal;
// Check Floor Number To Add Room To
int floorForRoomAdd =0;
int main() {
// Declaring Variables
int exitCheck = 0; // Used to loop if the user wants to check for more than date range
int choice;
// Creating Vector for Class Floor
vector<Floor> Building;
vector<Room> Floor;
vector<AccessPoint> Room;
// Calling the functions
cout << "How Many Floors Does This Building Contain? ";
cin >> floorTotal;
cout << endl;
for (int i = 0; i < floorTotal; i++) { // Gathers total floors number + How many rooms for each floor
fillFloor(Building);
cout << "How Many Rooms Are On This Floor? : " ;
cin >> roomNumber;
cout << endl;
for (int b = 0; b < roomNumber; b++) { // Gathers total Room number + How many access points for each room
fillRoom(Floor);
cout << "How Many Access Points Are In This Room? : ";
cin >> accessPointNumber;
cout << endl;
for (int c = 0; c < accessPointNumber; c++) { // Gather total access points + Status of each access point
fillAccessPoint(Room);
}
}
}
cout << "##############################################################" << endl;
cout << "# Done Building #" << endl;
cout << "##############################################################" << endl << endl;
while (exitCheck <1) {
// TITLE
cout<<"\nNETWORK MONITORING ACCESS POINTS \n";
cout<<"----------------------------------";
cout<<"\n1 - Display Building Information"; // Check (Some minor issue)
cout<<"\n2 - Add a Floor"; // Check
cout<<"\n3 - Delete a Floor"; // Check
cout<<"\n4 - Add a Room";
cout<<"\n5 - Delete a Room";
cout<<"\n6 - Add a Network Access Point";
cout<<"\n7 - Delete a Network Access Point";
cout<<"\n8 - Toggle Access Point Status";
cout<<"\n9 - Change Access Point Date";
cout<<"\n0 - Exit"; // Check
cout<<"\n";
// Input
cout<<"\nChoice: ";
cin>> choice;
// Determine Choice
if (choice == 1) {
cout << "##############################################################" << endl;
cout << "# The status of the building is #" << endl;
cout << "##############################################################" << endl << endl;
printFloorVector(Building); // Prints end result
cout << endl;
printRoomVector(Floor); // Prints end result
cout << endl;
printAccessPointVector(Room); // Prints end result
cout << endl;
}
else if (choice == 2) { // Adds a floor
fillFloor(Building);
cout << "Floor Has Been Created!" ;
//cin >> roomNumber;
//cout << endl;
}
else if (choice == 3) { // Deletes a floor
deletesFloor(Building);
}
else if (choice == 4) { // Adds a room
cout << "What Floor Would You Like To Add A Room To?";
cin >> floorForRoomAdd;
cout << endl;
replaceFloor(Building); //code where floor has the room info
cout << "How Many Rooms Are On This Floor? : " ;
cin >> roomNumber;
cout << endl;
}
else if (choice == 5) { // Deletes a room
cout << "What Floor Is The Room That You Would Like To Have Deleted?";
//code where floor has the room info
deletesRoom(Floor);
}
else if (choice == 6) { // Adds an access point
cout << "How Many Access Points Are In This Room? : ";
cin >> accessPointNumber;
cout << endl;
}
else if (choice == 7) { // Deletes an access point
}
else if (choice == 8) { // Changes access point status
}
else if (choice == 9) { // Change access point date
}
else if (choice == 0) { // Exits
exitCheck = 2;
}
else {
cout<< "Input Not Valid. Please Provide A Valid Input";
}
}
// Display the Purpose and that Program has now ended
cout << "\nThe Purpose Of This Program Is To Create A Building Network " << endl;
cout << "Access Operation That Uses Vectors, Clas Callings, And Loops" << endl;
cout << "\nThe Program Has Now Ended\n" << endl;
return 0;
}// End Program
void fillFloor(vector<Floor>& newBuilding) {
floorID++;
cout << "----------------------"<< endl;
cout << "Floor Numer: "<< floorID << endl;
cout << "----------------------"<< endl;
Floor newFloor (floorID, roomNumber); // This istantiated the object in vector, will be passing floorID and roomNumber to the new object
newBuilding.push_back(newFloor); // adds a new object to the newBuilding vector
cout << endl;
}
// Deletes Floor
void deletesFloor(vector<Floor>& newBuilding) {
int deletedFloor;
cout << "Enter Floor Number To Delete It"<< endl;
cin >> deletedFloor;
cout << "Floor Numer: "<< deletedFloor << " Has Been Deleted!" << endl;
deletedFloor = deletedFloor - 1;
newBuilding.erase(newBuilding.begin()+deletedFloor);
}
// Replace Floor Info
void replaceFloor(vector<Floor>& newBuilding) {
for (unsigned int i = 0; i < newBuilding.size(); i++) {
if (newBuilding[i].getFloorID() == floorForRoomAdd) {
int changeRoomTotal = newBuilding[i].getRoomNumber;
newBuilding[i].getRoomNumber = changeRoomTotal + 1;
}
}
}
// Insert New Room
void insertRoom(vector<Room>& newFloor) {
roomID++;
cout << "What Floor Will This Room Be Added In?"<< endl;
cout << "Room Numer: "<< roomID << endl;
cout << "----------------------"<< endl;
Room newRoom (roomID, accessPointNumber); // This istantiated the object in vector, will be passing floorID and roomNumber to the new object
newFloor.insert(newFloor.begin()+3, newRoom);
cout << endl;
}
void fillRoom(vector<Room>& newFloor) {
roomID++;
cout << "----------------------"<< endl;
cout << "Room Numer: "<< roomID << endl;
cout << "----------------------"<< endl;
Room newRoom (roomID, accessPointNumber); // This istantiated the object in vector, will be passing floorID and roomNumber to the new object
newFloor.push_back(newRoom); // adds a new object to the newFloor vector
cout << endl;
}
// Deletes Room
void deletesRoom(vector<Room>& newFloor) {
int deletedRoom;
cout << "Enter Room Number To Delete It"<< endl;
cin >> deletedRoom;
cout << "Room Number: "<< deletedRoom << " Has Been Deleted!" << endl;
deletedRoom = deletedRoom - 1;
newFloor.erase(newFloor.begin()+deletedRoom);
}
void fillAccessPoint(vector<AccessPoint>& newRoom) {
bool accessPointStatus;
accessPointID++;
cout << "----------------------"<< endl;
cout << "Access Point Number: "<< accessPointID << endl;
cout << "----------------------"<< endl;
cout << "What Is The Status Of This Access Point : ";
cin >> accessPointStatus;
AccessPoint newAccessPoint (accessPointID, accessPointStatus); // This istantiated the object in vector, will be passing floorID and roomNumber to the new object
newRoom.push_back(newAccessPoint); // adds a new object to the newFloor vector
cout << endl;
}
// This will display all of the building information
void printFloorVector(const vector<Floor>& newBuilding) {
cout << "The Building Has: " << floorTotal << " Floors" << endl;
unsigned int newBuildingSize = newBuilding.size();
for(unsigned int i = 0; i < newBuildingSize; i++) {
cout << "Floor ID: " << newBuilding[i].getFloorID() << endl;
cout << "Total Rooms: " << newBuilding[i].getRoomNumber() << endl;
}
}
void printRoomVector(const vector<Room>& newFloor) {
unsigned int newFloorSize = newFloor.size();
for(unsigned int a = 0; a < newFloorSize; a++) {
cout << "Room ID: " << newFloor[a].getRoomID() << endl;
cout << "Total Access Points: " << newFloor[a].getAccessPointNumber() << endl;
}
}
void printAccessPointVector(const vector<AccessPoint>& newRoom) {
unsigned int newRoomSize = newRoom.size();
for(unsigned int b = 0; b < newRoomSize; b++) {
cout << "Access Point Number: " << newRoom[b].getAccessPointID() << endl;
cout << "Access Point Status: " << newRoom[b].getAccessPointStatus() << endl;
cout << endl;
}
}

As far as I understand, you want to fix the replaceFloor function so that you can add one more room to a particular floor.
In the code, you correctly identify the position of the floor element inside the building vector using the line: if (newBuilding[i].getFloorID() == floorForRoomAdd)
In addition to the steps you have done, you also need to actually add the room to the floor vector. For that, you can access the floor vector as newBuilding[i] and then call newBuilding[i].push_back(newRoomObject) where newRoomObject contains all the information you have specified for the new floor to be added. This will result in the room to be added in the floor vector.
If I have misunderstood your query in any manner, please mention that so I may update my answer. One query which I have, but can't comment due to lack of reputation is, why have you used newFloor.insert(newFloor.begin()+3, newRoom); in the insert room function. The only reason for the +3 constant I can see is that you may be thinking that you are saying that the first two spots are taken up by floorID and room no. Even in that case, it should be +2. Also, even then, floorID and room no will most probably be two integers (or some number), whereas the rooms are objects. You cannot mix those types in an array. Please clarify.

Related

Cant seem to work a second for loop with a pointer for an array

I have a simple program that calculates for mpg using arrays and pointers
When I input miles, it works perfectly but when i input gallons I can only input until 5th. any advice?
At first when it was still a for loop it was until 3rd only but when i used try and catch it was until 5th
I tried changing ctr value after the first for loop where i inputted miles but it didnt change. I tried using do while and while loop and still
const int size = 10;
typedef double *pointers;
void Mperg();
void MilesPerrGallon(double *ptr1, double *ptr2);
char displayMenu(char *pt);
int main()
{
char sagot;
char *ptr;
ptr =& sagot;
displayMenu(ptr);
switch(sagot){
case '1':
Mperg();
break;
case '2':
cout << "toit";
break;
default:
cout << sagot << " is invalid";
break;
}
}
void Mperg(){
double miles[size], gallons[size];
int ctr;
pointers milPtr, galPtr;
system("cls");
cout<<"COMPUTING FOR MPG : miles per gallon...\n";
cout<<"MILES\n";
galPtr = &gallons[size];
milPtr = &miles[size];
for(ctr = 0; ctr<size; ctr++){
try{
cout << "miles[" << ctr << "]: ";
cin >> milPtr[ctr];
if(milPtr[ctr] < 100 || milPtr[ctr] > 250){
throw milPtr[ctr];
}
}
catch(double xmilPtr){
cout << milPtr[ctr] << " is invalid!.. 100-250 only\nreenter new value\n";
ctr--;
}
}
system("cls");
do{
for(ctr = 0; ctr<size; ctr++){
try{
cout << "gallons[" << ctr << "]: ";
cin >> galPtr[ctr];
if(galPtr[ctr] < 5 || galPtr[ctr] > 25){
throw galPtr[ctr];
}
}
catch(double xgalPtr){
cout << galPtr[ctr] << " is invalid!.. 5-25 only\nreenter new value\n";
ctr--;
}
}
}while(ctr<size);
}
char displayMenu(char *pt)
{
//add code here
cout << "---------O P T I O N S---------\n";
cout << "[1] Compute Miles Per Gallon" << endl;
cout << "[2] Sorting of Numbers" << endl;
cout << "[3] EXIT" << endl;
cout << "-------------------------------\n";
cout << "Enter your choice: ";
cin >> *pt;
return *pt;
}
Miles
Gallons
galPtr = &gallons[size];
milPtr = &miles[size];
Since size is 10, this:
Sets galPtr to point to the 11th element of gallons.
Set milPtr to point to the 11th element of miles.
That's what the above code means in C++.
Of course, both arrays have only ten values, and attempting to obtain a pointer and using the pointer to modify the 11th, and subsequent, values in both arrays is undefined behavior.
You obviously meant to implement galPtr=gallons and milPtr=miles, here, although there is no real reason to use pointers this way, it doesn't accomplish anything.

C++ function in switch statement is not executing

I'm new to c++ and I'm trying to make a simple class roster program that accepts new students storing the student data in an array that then be sorted and display the contents of the array. However when running the program and entering the menu selection, two of the three functions do not work. Any help or guidance is much appreciated. My code is here.
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
//Create Students class
class Students
{
public:
char sFirstName[256];
char sLastName[256];
int sStudentID;
double sGrade;
double sGPA;
double nCreditHours;
};
//functions
Students addStudent();
//void displayRoster();
//void sortRoster();
void showMenu();
void showWelcome();
//Welcome function
void showWelcome()
{
cout << "Welcome to my class roster program. \n"
<< "This program can be used to add students to the roster, \n"
<< "which can then be sorted by either name or I.D. number. \n"
<< endl;
}
//Menu function
void showMenu()
{
cout << " Student Roster: \n"
<< "MAIN MENU PLEASE SELECT AN OPTION" << endl;
cout << "1) Add student to roster: " << endl;
cout << "2) Display current roster: " << endl;
cout << "3) Sort roster: " << endl;
cout << "4) Exit program: " << endl;
//cout << "5) Display roster sorted by 'student I.D.': " << endl;
//cout << "6) Display roster sorted by 'Grade': " << endl;
//cout << "7) Display roster sorted by 'GPA': \n" << endl;
cout << " Make your selection: \n" << endl;
}
//Add student function
Students addStudent()
{
Students student;
cout << "Add student to roster. \n"
<< "Enter first name: " << endl;
cin >> student.sFirstName;
cout << "Enter last name: " << endl;
cin >> student.sLastName;
cout << "Enter student I.D.: " << endl;
cin >> student.sStudentID;
return student;
}
void displayStudent(Students student)
{
cout << "Student name: " << student.sFirstName << " "
<< student.sLastName << endl;
cout << "I.D. # " << student.sStudentID << endl;
}
void displayRoster()
{
Students student[256];
int nCount;
for (int index = 0; index < nCount; index++)
{
displayStudent(student[index]);
}
}
int getStudents(Students student[], int nMaxSize)
{
int index;
for (index = 0; index < nMaxSize; index++)
{
char uInput;
cout << "Enter another student to the roster? (Y/N): ";
cin >> uInput;
if (uInput != 'y' && uInput != 'Y')
{
break;
}
student[index] = addStudent();
}
return index;
}
void sortRoster()
{
Students student[256];
int nCount;
//bubble swap
int nSwaps = 1;
while (nSwaps != 0)
{
nSwaps = 0;
for (int n = 0; n < (nCount - 1); n++)
{
if (student[n].sStudentID > student[n+1].sStudentID)
{
Students temp = student[n+1];
student[n+1] = student[n];
student[n] = temp;
nSwaps++;
}
}
}
}
int main()
{
int selection; //menu selection variable
//constants for menu selection
const int ADD_STUDENT = 1,
DISPLAY_ROSTER = 2,
SORT_ROSTER = 3,
QUIT_PROGRAM = 4;
Students student[256];
//int nCount = getStudents(student, 256);
do
{
showWelcome(); //Show welcome message
showMenu(); //Show menu options
cin >> selection;
while (selection < ADD_STUDENT || selection > QUIT_PROGRAM)
{
cout << "Enter a valid selection: ";
cin >> selection;
}
if (selection != QUIT_PROGRAM)
{
switch (selection)
{
case ADD_STUDENT:
addStudent();
break;
case DISPLAY_ROSTER:
displayRoster();
break;
case SORT_ROSTER:
sortRoster();
break;
}
}
}
while (selection != QUIT_PROGRAM);
return 0;
}
The problem is not in the switch.
The addStudent() is not adding the student into any list or array. Also since it return type is Students you should add it into the any array of Students. Since you have not stored any data display won't display anything.
The another problem is of nCount. You are using it in for comparison without initializing it. Also to keep nCount synchronized either make it global, use as pointer or handle it with return.
Also the problem is in displayRoster(). You are declaring Students array as Students student[256]; and you are using it without initializing. Also if initialized, it won't have the data which was given as input.
NOTE: Sit and read your code again, there are many more mistakes. Try visualizing how your data should be stored and how your code is to behave and then start writing code.
Your nCount is not initialised. Since this variable is used in those two functions (and assuming that it refers to the total count), you can declare it as a global variable:
nCount=0;
Everytime you add a new entry, you can increment the counter as:
nCount++;
Another suggestion to make your code actually work:
student[i++]=addStudent();
where i is a counter initialised to 0. Your addStudent() function returns an object, and you discard it. Store it in the array of objects you created:
Students student[256];
Also, since you use the above in almost all functions, it is best to declare it as global rather than redeclaring in each function.

How do I permenantly delete a row of arrays and shift a row of arrays upwards?

I've been assigned by school to create an application that contains a book list with 20 different books in it and build a menu with following options:
(a) List – Display the list in tabular format. Each display should contain an appropriate heading and column captions;
(b) Search – Search for a book record in the list using the ISBN and print the full record for the book;
(c) Delete – Delete an existing book record from the list;
(d) Exit – Stop the program.
Here is the sample of my program:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <cctype>
using namespace std;
typedef struct
{
char code[50];
char author[50];
char name[50];
char edition[50];
char publish[50];
char price[50];
} BOOK_LIST;
void list (BOOK_LIST book[], int rows);
void showBook (BOOK_LIST book[], int rows);
void updateRecord (BOOK_LIST book[], int rows);
void advancedSearch (BOOK_LIST book[], int rows);
int deleteBook (BOOK_LIST book[], int rows);
int searchBook(BOOK_LIST book[], int rows);
int main()
{
ifstream inFile("list.txt");
if(!inFile)
cout << "Error opening input file\n";
else
{
BOOK_LIST books[50];
int index = -1, choice;
inFile.getline(books[++index].code, 50);
while(inFile)
{
if(inFile.peek() == '\n')
inFile.ignore(256, '\n');
inFile.getline(books[index].author, 50);
inFile.getline(books[index].name, 50);
inFile.getline(books[index].edition, 50);
inFile.getline(books[index].publish, 50);
inFile >> books[index].price;
// read next number
inFile >> books[++index].code;
}
inFile.close();
// menu starts
do
{
cout << "Do you want to:\n";
cout << "1. List all books\n";
cout << "2. Get details about a book\n";
cout << "3. Delete a book from the list\n";
cout << "4. Exit\n";
cout << "5. Advanced Search\n";
cout << "Enter choice: ";
cin >> choice;
switch (choice)
{
case 1 : list(books, index);
break;
case 2 : showBook(books, index);
break;
case 3 : updateRecord(books, index);
break;
case 5 : advancedSearch(books, index);
case 4 : break;
default: cout << "Invalid choice\n";
}
} while (choice != 4);
ofstream outFile("list.txt");
if(!outFile)
cout << "Error opening output file, records are not updated.\n";
else
{
for (int i = 0; i < index; i++)
{
outFile << books[i].code << endl;
outFile << books[i].author << endl;
outFile << books[i].name << endl;
outFile << books[i].edition << endl;
outFile << books[i].publish << endl;
outFile << books[i].price << endl;
}
outFile.close();
}
}
return 0;
}
void list(BOOK_LIST book[], int rows)
{
cout << fixed << setprecision(2);
cout << "ISBN\t Author BookName Edition\tPublisher\t Price\n";
for (int i = 0; i < rows; i++)
cout << book[i].code << "\t" << book[i].author << "\t"
<< book[i].name << "\t" << book[i].edition << "\t"
<< book[i].publish << "\t"
<< " " << book[i].price << endl;
return;
}
int searchBook(BOOK_LIST book[], int rows)
{
int i = 0;
bool found = false;
char code[50];
cout << "Enter an ISBN code of a book to search: ";
fflush(stdin);
cin.getline(code, 50);
while (i < rows && !found)
{
if (strcmp(code, book[i].code) == 0)
found = true;
else
i++;
}
if (found)
return i;
else
return -1;
}
void showBook(BOOK_LIST book[], int rows)
{
int pos = searchBook(book, rows);
if (pos != -1)
{
cout << "Author is " << book[pos].author << endl;
cout << "Book name is "<< book[pos].name << endl;
cout << book[pos].edition << " Edition" << endl;
cout << "The publisher of this book is " << book[pos].publish << endl;
cout << "Current price is " << book[pos].price << endl;
}
else
cout << "Product not found\n";
return;
}
void updateRecord(BOOK_LIST book[], int rows)
{
int pos = deleteBook(book, rows);
char code [50];
int i,j = 0;
for(i = 0; i < rows ; i++)
{
if(strcmp(code, book[i].code))
{
strcpy(book[j].code , book[i].code);
strcpy(book[j].author, book[i].author);
strcpy(book[j].name, book[i].name);
strcpy(book[j].edition, book[i].edition);
strcpy(book[j].publish, book[i].publish);
strcpy(book[j].price, book[i].price);
j++;
}//if
else
{
i++;
strcpy(book[j].code, book[i].code);
strcpy(book[j].author, book[i].author);
strcpy(book[j].name, book[i].name);
strcpy(book[j].edition, book[i].edition);
strcpy(book[j].publish, book[i].publish);
strcpy(book[j].price, book[i].price);
j++;
}//else
}//for
return;
}
int deleteBook (BOOK_LIST book[], int rows)
{
int i = 0;
bool found = false;
char code[50];
cout << "Enter an ISBN code of a book to delete: ";
fflush(stdin);
cin.getline(code, 50);
while (i < rows && !found)
{
if (strcmp(code, book[i].code) == 0)
found = true;
else
i++;
}
if (found)
return i;
else
return -1;
}
void advancedSearch (BOOK_LIST book[], int rows)
{
char advanced[50];
cout << "Please enter either the author's name or the book name to search: ";
fflush(stdin);
cin.getline(advanced, 50);
for(int i = 0; i < rows; i++)
{
if(strstr(book[i].author, advanced) || strstr(book[i].name, advanced))
{
cout << "ISBN is " << book[i].code << endl;
cout << "Author is " << book[i].author << endl;
cout << "Book name is " << book[i].name << endl;
cout << book[i].edition << " Edition" << endl;
cout << "Publisher is " << book[i].publish << endl;
cout << "Current price is " << book[i].price << endl;
}
}
return ;
}
The problem starts here:
When I want to permanently delete a whole row of book record. But the book record is still there after deleting.
First, this is my menu, then I press 1 to check the list for the IBSN. Then, I press 3 to proceed to the deleting part. At that time, I choose TheHost to delete. After the deleting, to ensure that I have deleted the chosen book, so I press 1 to check the list again, but unfortunately the book is still there:
If I am able to delete a book record, and how do I delete a record permanently? And after deleting a record, how do I move the remaining records upwards, so that it won't leave any empty row there?
The function for the deleting:
void updateRecord(BOOK_LIST book[], int rows)
{
int pos = deleteBook(book, rows);
char code [50];
int i,j = 0;
for(i = 0; i < rows ; i++)
{
if(strcmp(code, book[i].code))
{
strcpy(book[j].code , book[i].code);
strcpy(book[j].author, book[i].author);
strcpy(book[j].name, book[i].name);
strcpy(book[j].edition, book[i].edition);
strcpy(book[j].publish, book[i].publish);
strcpy(book[j].price, book[i].price);
j++;
}//if
else
{
i++;
strcpy(book[j].code, book[i].code);
strcpy(book[j].author, book[i].author);
strcpy(book[j].name, book[i].name);
strcpy(book[j].edition, book[i].edition);
strcpy(book[j].publish, book[i].publish);
strcpy(book[j].price, book[i].price);
j++;
}//else
}//for
return;
}
The Text file that I used in this program a.k.a the BOOK_LIST
I see (at least) two problems with your code around deleting a book.
in update_record you're using a char code[50] which is being used to compare with strcmp later on but is not initialized.
when you delete a book you should update your index which becomes rows in the update_record method. However index is passed to rows by value which means that even if you try running --rows; in update_record it won't decrement index. You'll need to pass it by reference for it to update index.
On a side note, I agree with comments regarding fixing your code to use vectors/maps & strings instead of simple arrays and char*.
But since you mentioned it was a school task I would guess you haven't reached that sort of material yet.
Good Luck.
The assignment most probably expects you to use std::list template rather than the classical C array. Insertion and deletion is natural for lists.
An alternative would be to use std:map using the ISBN as a key. ISBN is supposed to be globally unique.
Just to expand on my comment, here is one way to remove an element from an array.
Suppose we have an array of char called X, containing {'a', 'b', 'c', 'd', 'e', 'f'}, and we want to get rid of 'c'.
If we want to maintain the order of the remaining elements, then what we're aiming for is {'a', 'b', 'd', 'e', 'f'}. So we copy the 'd' into the 'c' place, the 'e' into the old 'd' place, and so on:
a b c d e f
a b d d e f
a b d e e f
a b d e f f
We can do this with code like
for(int k=2; k<5; ++k)
X[k] = X[k+1];
And what happens to that extra 'f' at the end? We could write some placeholder into that unwanted space, and then watch out for that placeholder for the rest of the run. Or, we could just stop using that space, and say that from now on we're considering an array of length 5. That extra 'f' will still be there, but for now we don't care about what exists past the end of our array.
(If we don't care about the order of the remaining elements, then we can make this a lot simpler.)
Remember, it's always easier to develop new functionality in isolation.
Once you have this working, you can apply it in your code and get a passing grade, but if you really want to learn something useful you should write a Book class.

How to use a dynamically sized array of structs?

I have to make my homework. It is console application which uses an array of structs that keep information about a computer(brand, year of manufactoring, weight and inventory number). So I wrote a completely working program, but I want to use a dynamic array, because I dont know how many records the user will input.
Is there way to do this. To add new records in array until the user say n/N? Any suggestions?
This is my version of program:
#include "stdafx.h"
#include <iostream>
using namespace std;
struct ComputerInfo
{
char computerMark[20], invertarNumber[6];
unsigned int year;
float weight;
};
ComputerInfo computerArray[300];
ComputerInfo AddComputers(ComputerInfo compterArray[], int counter)
{
cout << "Enter mark of the computer: ";
cin >> computerArray[counter].computerMark;
cout << "Enter year of establish: ";
cin>> computerArray[counter].year;
while ((computerArray[counter].year < 1973)
|| (computerArray[counter].year > 2013))
{
cout << "INVALID YEAR!!!" << endl;
cout << "Enter year of establish: ";
cin>> computerArray[counter].year;
}
cout << "Enter computer weidth: ";
cin >> computerArray[counter].weight;
cout << "Enter computer invertar number(up to six digits): ";
cin >> computerArray[counter].invertarNumber;
return computerArray[counter];
}
void ShowRecords()
{
int counter = 0;
while (computerArray[counter].year != 0)
{
cout << "Mark: " << computerArray[counter].computerMark << endl;
cout << "Year: " << computerArray[counter].year << endl;
cout << "Weidth: " << computerArray[counter].weight << endl;
cout << "Inv. number: " << computerArray[counter].invertarNumber << endl << endl;
counter++;
}
}
void MoreThanTenYearsOld(ComputerInfo computerArray[])
{
int counter = 0;
float counterOldComputers = 0;
float computerPer = 0;
while (computerArray[counter].year == 0)
{
if (computerArray[counter].year <= 2003)
{
counterOldComputers++;
}
counter++;
}
computerPer = counterOldComputers / 3;
cout << endl;
cout << "Percantage of old computers is: " << computerPer << endl;
}
int main()
{
int counter = 0;
float computerPer = 0;
char answer = 'y';
for (int i = 0; i <= 299; i++)
{
strcpy(computerArray[i].computerMark,"");
}
while((answer == 'Y') || (answer == 'y'))
{
computerArray[counter] = AddComputers(computerArray, counter);
cout << endl;
cout << "Do you want to enter more records (Y/N): ";
cin >> answer;
cout << endl;
counter++;
}
MoreThanTenYearsOld(computerArray);
return 0;
}
Yes. Instead of your array, use
std::vector<ComputerInfo> computerArray;
and you can add as many objects as you want:
ComputerInfo c;
// read the data
computerArray.push_back(c);
now, computerArray[0] will have the info in c.
You'll need to #include <vector>.
Also, instead of char computerMark[20] you can use a std::string.
You have two options:
1) Use std::vector instead of an array. This is a very powerful tool and certainly worth learning how to use.
2) Dynamically allocate the array and resize it as you add more items. Basically this means writing your own version of std::vector. This is a good way to strengthen your programming skills. You will learn what goes into writing standard classes and functions. However, I advise using std::vector in more serious programming because it has already been thoroughly tested and debugged.

Functions and structures in C++

/*I got stumped within my code. I think classes will be simpler than structures, but the chapter within my book makes me do structures. : / I am currently getting an error message that my function was not matched up for an overloaded function. The book does talk about them, but the examples of overloading functions in the book aren't helping me out. Also the book wants me to enter account numbers and fill in the objects and when they are asked for an account number they should have the opportunity to "QUIT" entering numbers and proceed onto the next part of the program; that whole way of thinking has my brain a bit fried and I was hoping I could get some help. I apologize if the formatting of my code is messy, I tried to reformat it within here so it would all go into the code brackets.
The Error happens at line... 161 at the displayAccounts function. Parameters were different within the top and bottom of the two functions I changed it and it works. I am going to go over different parts and if its correct post the correct code.*/
I figured out exactly the question that I need. I need the "QUIT" loop to be allowed to be followed up within the account numbers. This would allow the user to enter in a 0 at any time when asked to enter an account number and this was what was confusing me the most.
#include <iostream>
#include <iomanip>
using namespace std;
struct BankAccount
{
void enterAccountsData(BankAccount *accounts);
void computeInterest(BankAccount *accounts);
void displayAccounts(BankAccount *accounts, const int QUIT);
int accountNum; // holds the account number.
double accountBal; // holds the account balance.
double annualInterest; // holds the interest rate.
int term; // holds the term for the accounts.
};
int main()
{
const int MAX_ACCOUNTS = 100; // The maximum number of bank accounts.
const int QUIT = 0; // sentinal value.
int input;
int num = 0;
BankAccount data[MAX_ACCOUNTS];
BankAccount display;
cout << "Enter " << QUIT << " to stop, otherwise enter 1 and procreed.";
cin >> input;
while(true)
{
if(input != QUIT)
{
data[MAX_ACCOUNTS].enterAccountsData(data);
data[MAX_ACCOUNTS].computeInterest(data);
}
else
{
break;
}
}
display.displayAccounts(data, QUIT);
//system("pause");
return 0;
}
void BankAccount::enterAccountsData(BankAccount *accounts)
{
cout << setprecision(2) << fixed;
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts. (change the number for more bank accounts)
int found;
int quit = 0;
/* First for loop which asks and holds the account information
entered in by the user. */
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
do
{
found = 0;
cout << "Enter in account # " << (num + 1) << endl;
cin >> accounts[num].accountNum; // holds the value of the account number
// Checks if the account number is valid.
while(accounts[num].accountNum < 999 || accounts[num].accountNum > 10000)
{
cout << "Account number must be four didgets:" << endl;
cin >> accounts[num].accountNum;
}
// Checks if the account numbers are the same.
for(int check = 0; check < num; check++)
{
while(accounts[num].accountNum == accounts[check].accountNum)
{
cout << endl << "Account Numbers cannot be the same, enter in a new account number." << endl;
found = 1;
break;
}
}
} while(found); // end of do while.
// Holds the values for the account balances.
cout << "Enter the accounts balance." << endl;
cin >> accounts[num].accountBal;
// Makes sure that the account balance is not negative.
while(accounts[num].accountBal < 0)
{
cout << "Account cannot have a negitive balance." << endl;
cin >> accounts[num].accountBal;
}
// Holds the interest rate.
cout << endl << "Enter the interest rate for account # " << (num + 1) << endl;
cin >> accounts[num].annualInterest;
// Makes sure the interest rate is valid
while(accounts[num].annualInterest > 0 && accounts[num].annualInterest > 0.15)
{
cout << endl << "Annual interest must be from 0 to 0.15." << endl;
cin >> accounts[num].annualInterest;
}
// Makes sure the interest rate is not negetive
while(accounts[num].annualInterest < 0)
{
cout << endl << "Interest rate cannot be negetive" << endl;
cin >> accounts[num].annualInterest;
}
// Holds the value for the length of the interest.
cout << endl << "How many years will this interest rate be held for? " << endl;
cin >> accounts[num].term;
//Checks for valid length of time for the term held
while(accounts[num].term < 0 || accounts[num].term > 11)
{
cout << "The Term must be greater than 1 and should not exceed 10" << endl;
cin >> accounts[num].term;
}
}
cout << "If you wish to stop enter 0 otherwise type 1 to proceed" << endl;
cin >> quit;
if(quit = 0)
{
return;
}
}
void BankAccount :: computeInterest(BankAccount *accounts)
{
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts.
const int MONTHS_IN_YEAR = 12;
double total = 0;
double average = 0;
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
/*Goes through the term year and calculates the total
of each account balance. Then calculates the average. */
for(int year = 0; year < accounts[num].term; year++)
{
for(int month = 0; month < MONTHS_IN_YEAR; month++)
{
accounts[num].accountBal = (accounts[num].accountBal * accounts[num].annualInterest) + accounts[num].accountBal;
}
int month = 1;
cout << endl << "Total amount for account # " << (num + 1) << " is: " << accounts[num].accountBal << endl ;
total += accounts[num].accountBal;
cout << endl << "The total amount of all accounts is: " << total << endl;
}
}
average = total / NUM_OF_ACCOUNTS;
cout << "Average of all the bank accounts is: " << average << endl;
}
void BankAccount :: displayAccounts(BankAccount *accounts)
{
int input = 0;
int found;
const int MAX_ACCOUNTS = 100;
int quit = 0;
cout << endl << "Which account do you want to access?" << endl <<
"To stop or look at none of the account numbers type: " << quit << endl;
cin >> input;
for(int num = 0; num < MAX_ACCOUNTS; num++)
{
while(num < MAX_ACCOUNTS && input != accounts[num].accountNum)
{
num++;
}
if(input == accounts[num].accountNum) // This if sees if an account matches what the user entered.
{
cout << "Account: " << accounts[num].accountNum << endl << "Balance is: " <<
accounts[num].accountBal << endl << "Interest rate is: " << accounts[num].annualInterest;
cout << endl << "Enter another account number or type 0 to quit." << endl;
found = 1;
cout << endl;
cin >> input;
}
if(found == 0)
{
cout << "Sorry that account doesn't exist. Enter another account number." << endl;
cin >> input;
}
}
}
In C++, classes and structs are exactly the same constructs. They are, in fact, one thing — a User-Defined Type.
There is a different that is invoked depending on whether you used the keyword struct or class to define your UDT, and that is that class-key defaults to private member access and private inheritance, whereas struct-key defaults to both being public.
Other than this syntax difference, you can use either without worrying about one being "simpler" than the other.
Anyway, your compiler error (please provide it next time) is probably due to a declaration/definition mismatch.
Your declaration:
void displayAccounts(BankAccount *accounts, const int QUIT);
Start of your definition:
void BankAccount :: displayAccounts(BankAccount *accounts) {
The start of the definition should be
void BankAccount::displayAccounts(BankAccount* accounts, const int QUIT) {
to match. I've also fixed your spacing to be nicer. :)
void displayAccounts(BankAccount *accounts, const int QUIT);
... looks different between declaration and definition. Second parameter is missing in the definition.
Not sure what your question is, but classes and structs in C++ are equivalent except that fields are public by default in structs, but private by default in classes.
In the struct’s displayAccounts() member declaration you have:
void displayAccounts(BankAccount *accounts, const int QUIT);
and when defining the method later:
void BankAccount :: displayAccounts(BankAccount *accounts)
You have just missed
const int QUIT
parameter for the member function definition.