C++ function in switch statement is not executing - c++

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.

Related

printing name in multiple for loops and arrays

I've come across a little problem, how do I print the winning candidate's name? See the instructions here are, input five names, their number of votes and percentage of votes, whoever has the highest wins. I don't know if I did my code right, but it works.. well except for the name part. I've tried everything from a lot of for loops to transfer the array or what.
I'm almost done with the code.
Here's the code
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char candidates[50];
int votes[5]={0};
float percent[5]={0};
int a,b,c,d,e,i;
int maxx;
int champ=0;
char winner[50];
cout << "Enter the candidates' last names: ";
cout << endl;
for(a=1;a<=5;a++)
{
cout << a << ". ";
cin >> candidates;
}
cout << endl;
cout << "Enter their number of votes: " << endl;
for(b=1;b<=5;b++)
{
cout << b << ". ";
cin >> votes[b];
}
cout << endl;
cout << "percentage of votes: " << endl;
for(c=1;c<=5;c++)
{
cout << c << ". ";
percent[c]=votes[c]*0.2;
printf("%.2f\n", percent[c]);
}
cout <<"Candidates\t\tVotes\t\t% of Votes" << endl;
for(int k=1;k<=5;k++)
{
cout << candidates[k] << "\t\t\t" << votes[k] << "\t\t\t";
printf("%.2f\n", percent[k]);
}
maxx=percent[0];
for(d=1;d<=5;d++)
{
if(maxx<percent[d]);
{
//what happens here?
}
}
return 0;
}
You should keep a 2d array of characters or array of string for storing candidate names instead of a 1-d array.
char candidates[5][10]; //
for(int i = 0; i < 5; i++)
{
cin >> candidates[i];
}
Then keep a variable to store index for winning candidate
int winIndex = 0;
int winPercent = 0;
for(int i = 0; i < 5; i++)
{
if(percent[i] > winPercent)
{
winPercent = percent;
winIndex = i;
}
}
Finally print name of winning candidate;
cout << candidates[winIndex];
In object oriented approach, you may create a class with following information
class Candidate
{
string name;
int votes;
float percent;
};
Use string candidates[50]; instead of char candidates[50];
then cin >> candidates[a];

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.

Changing a Second Value withing a Vector Object in 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.

Sorting names between a Student class

edit. I want to thank the two people who helped me in my code. I fixed my coding as of 7:22 PM PST 9/25/2014. Still having trouble with the sorting though.
So I'm trying to teach myself how to use C++ in order to get ahead of my programming class in school. I've already taken Java so I'm relatively familiar with the structure of the coding but not exactly sure what to be typing. This practice problem is:
1)Ask the user how many people he wants to enter into the list.
2)Read 3 strings, then turn that info into a student class and put the student inside a vector.
3)Sort the list by name. (Extra credit would be to sort the list by Student ID)
4)Print the info of each student in the list.
5)Ask user while answer is 'Y', search the list for a name and print the info correlating to the name
While in Java, this seems pretty easy, I'm having an extremely hard time understanding what is going on in C++.
I currently only have 1, 2, 4 and 5 done. This is what I have so far.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <iomanip>
using namespace std;
class Student
{
string myName, myStudentID, myClassID;
public:
Student(string name, string studentID, string classID)
{
myName = name;
myStudentID = studentID;
myClassID = classID;
}
string getName() { return myName; }
string getStudentID() { return myStudentID; }
void printInfo() { cout << myName << setw(15) << myStudentID << setw(10) << myClassID << endl; }
};
int main()
{
int num;
std::vector<Student> studentList;
cout << "How many students do you wish to add to the student list ? " << endl;
cin >> num;
cin.ignore();
for (int a = 0; a < num; a++)
{
string inputName, inputStudentID, inputClassID;
//get name
cout << "Please enter the Student name : ";
getline(cin, inputName);
//get student ID
cout << "Please enter the Student ID number : ";
getline(cin, inputStudentID);
//get class ID
cout << "Please enter the Student class ID : ";
getline(cin, inputClassID);
Student thisStudent(inputName, inputStudentID, inputClassID);
studentList.push_back(thisStudent);
cout << endl;
}
//sort(studentList.begin(), studentList.end());
/*
I never figured out how to sort the list by name.
I do not know how to compare the name of studentList[0] and studentList[1]
to put them in alphabetical order.
*/
cout << endl;; // FORMATTING
cout << "The student list has a size of " << studentList.size() << endl;
cout << endl;; // FORMATTING
cout << "Student Name" << setw(15) << "Student ID" << setw(10) << "Class ID" << endl;
for (int a = 0; a < studentList.size(); a++)
{
studentList[a].printInfo();
}
cout << endl;; // FORMATTING
string searchedName;
char answer;
do
{
cout << endl;; // FORMATTING
cout << "Please type the name of the person you want to search for: ";
getline(cin, searchedName);
for (int a = 0; a < studentList.size(); a++)
{
if (searchedName.compare(studentList[a].getName()) == 0)
{
studentList[a].printInfo();
break;
}
else
if (a == (studentList.size() - 1)) //If went to end of the list, tell them name not found.
cout << "There is no " << searchedName << " in the list. \n";
}
cout << "Would you like to search for another person? \n";
cout << "Y for Yes, N for No. \n";
cin >> answer;
cin.ignore();
} while (answer == 'Y' || answer == 'y');
return 0;
}
You could create a static compare function in class Student to use with std::sort
class Student
{
string myName, myStudentID, myClassID;
// ...
static bool compare_name(const Student & lStudent, const Student & rStudent)
{return (lStudent.myName < rStudent.myName);}
};
// ...
std::sort(studentList.begin(), studentList.end(), Student::compare_name);
or if your compiler supports lambda functions:
std::sort(studentList.begin(), studentList.end(),
[studentList](const Student & lStudent, const Student & rStudent)
{return (lStudent.myName < rStudent.myName);});

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.