C++, structure database program issues - c++

I apologize if this is in the wrong place. I didn't really see an area where to post specific code problems.
I'm tasked by my professor to create a program that allows a user to insert, edit and print out a database of clients. I'm having a problem with one of my functions, it doesn't seem to be comparing something well. The function is the EditClient function on line 85, the logic problem I'm having is on line 93. I included a few tests in the code that makes me certain it is line 93, for example in the else statement on line 99 I have it printing out the same arguments being used in the comparison. Which works! I'm clueless as to why it's not understanding the comparison.
#include <iostream>
#include <iomanip>
using namespace std;
struct ClientInfo{ // the structure template for the client info
char name[40]; //client name
char state[40]; //client state
char city[40];
int PhoneNumber;
long double AccountBalance; //accounts balance
char PaymentDate; //payment date
};
ClientInfo ClientList[10]; //intializes an array with the data type clientinfo
void MainMenu();
void NewClient(ClientInfo List[]); // prototypes
void ViewClient(ClientInfo List[]);
void EditClient(ClientInfo List[]);
int main(){
MainMenu();
system("pause");
}
void MainMenu(){ //this function is the main menu function
char choice = 4;
bool loop = true;
while (loop){
cout << "Welcome to the client database, enter 1 to view the clients, 2 to edit a client , and 3 to enter an entire new client. 0 to quit" << endl; //main menu prompt
cin >> choice;
if (choice == '1'){
ViewClient(ClientList);
}
else if (choice == '2'){
EditClient(ClientList);
}
else if (choice == '3'){
NewClient(ClientList);
}
else if (choice == '0'){
cout << "thank you for using the client database, closing out now" << endl;
loop = false;
}
else{
cout << "invalid number" << endl;
}
}
}
void NewClient(ClientInfo List[]){//function that goes through cins to insert client data
int desiredTimes = 0; // the number of clients the person wish to enter
cout << "how many clients are you entering ?, your list current has "<<endl;
cin >> desiredTimes;
cout << "entering new client function..." << endl;
for (int cnt = 0; cnt < desiredTimes; cnt++){ // runs the program exactly the amount of times the person wished.
cout << "please enter client name" << endl;
cin.ignore();
cin.getline(List[cnt].name, 40);
cout << "please enter client state" << endl; // the getline is used here because there may be spacings within these first 3 catagories
cin.getline(List[cnt].state, 40);
cout << "please enter client city" << endl;
cin.getline(List[cnt].city, 40);
cout << "please enter client Phone Number" << endl;
cin.ignore(); // this is used to prevent the getline from causing issues with the cin
cin >> List[cnt].PhoneNumber;
cout << "please enter client Account Balance" << endl;
cin >> List[cnt].AccountBalance;
cout << "please enter client Payment Date" << endl;
cin >> List[cnt].PaymentDate;
}
}
void EditClient(ClientInfo List[]){ // function to search for a name requested and display the info
char name[40];
cout << "what is the name of the client you wish to view (be specific)?";
cin >> name;
bool loop = true; // boolean for the loop
int cnt = 0; // position in the array
while (loop){
if (cnt < 11){
if (name == List[cnt].name){ //if true, prints out the client's info
cout << "true";
/*NewClient(List[cnt]);*/
loop = false; // ends the loop
}
else{
cout << name << " " << List[cnt].name << endl;
cnt++;
}
}
else{
cout << "your client isn't in the database M8" << endl;
loop = false;
}
}
}
void ViewClient(ClientInfo List[]){//this function goes through the client list and displays a particular client
cout << "the following is a huge overrun of all the data inside this list, prepare your self." << endl;
for (int cnt = 0; cnt <= 10; cnt++){//goes through until the counter is greater than the size of the list in the parameter
cout << endl;
cout << List[cnt].name;
cout << List[cnt].state;
cout << List[cnt].city;
cout << List[cnt].PhoneNumber;
cout << List[cnt].AccountBalance;
cout << List[cnt].PaymentDate;
}
}
this is the specific line, where i'm having a comparision error.
if (name == List[cnt].name){ //if true, prints out the client's info

if (name == List[cnt].name) is doing a pointer comparison, not a string comparison. This will only be true if name and List[cnt].name point to the same memory location, which they never will. You should probably be using std::string instead of char[], but if you need to use char[] for some reason, you'll need to use the strcmp() function to compare them.

instead of the if statement you are using, trying using this statement,
if (strcmp(name,List[cnt].name)==0){
It should work properly :)

Related

University assignment, cant run program as intended

So im trying to run a program that receives a set data from a file that updates each time the program is run and new data is added. But when i try to run it the program terminates after trying to receive input from user.The full code is as follow, im using devc++ if that matters
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
struct Deets
{
string NameSite[];
string AddressName[];
int numVaccine[];
int numStall[];
string DateVax[];
string ContNum[];
};
void Outputmenu();
int AddData(int,struct Deets V);
void EditData(int,struct Deets V);
void ShowExisting(int,struct Deets V);
void ClearArr(int,struct Deets V);
int main()
{
int i;
ifstream r("Total.txt");
r>>i;
r.close();
Deets V;
ifstream a;
a.open("Data.txt");
for(int c=0;c<=i;c++)
while(a>>V.NameSite[c]>>V.AddressName[c]>>V.numVaccine[c]>>V.numStall[c]>>V.DateVax[c]>>V.ContNum[c]);
a.close();
int menuS;
do
{
Outputmenu();
cout<<"\nPlease choose from 1-4, press 0 to close menu"<<endl;
cin>>menuS;
if (menuS==1)
AddData(i,V);
else if (menuS==2)
EditData(i,V);
else if (menuS==3)
ShowExisting(i,V);
else if (menuS==0)
cout<<"Thank you for your cooperation, We hope to see you soon! \nClosing program..,";
else
cout<<"Error, not within selection"<<endl;
}
while (menuS!=0);
ofstream b("Data.txt");
for(int c=0;c<=i;c++)
while(b<<V.NameSite[c]<<" "<<V.AddressName[c]<<" "<<V.numVaccine[c]<<" "<<V.numStall[c]<<" "<<V.DateVax[c]<<" "<<V.ContNum[c]<<endl);
return 0;
}
void Outputmenu() //instruction about the command for the user
{
cout << " -hello there!- " << endl;
cout << "===================================================================" << endl;
cout << " ***PLEASE CHOOSE ONE OF THE OPTION BELOW*** " << endl;
cout << "===================================================================" << endl;
cout << "\t1. Add Data (about Vaccination Center)" << endl;
cout << "\t2. Edit Data" << endl;
cout << "\t3. Show Existing Data" << endl;
cout << "\t0. Close Program" << endl;
cout << "===================================================================" << endl;
}
int AddData(int c, struct Deets A)
{
bool rq;
int i = c;
cout<<"Enter your company name/ institute name : ";
cin.ignore();
getline(cin,A.NameSite[i]);
cout<<"\n\t\t Safety Measure"<<endl;
cout<<"-Maintain a distance of 1 meter between one other access to vaccine doses.\n"<<"-Have a dedicated toilets for patient\n"<<"-Ability to maintain room temperature between 19 – 25 degrees \n"<<"-Have an adequate place for patients to wait "<<"\n-Have adequate sharps disposal bins, appropriate for the volume of patients, and securely placed and spaced to mitigate the risk of needle stick injuries."<<endl;
cout<<"-Adequate handwashing facilities for staff, and antimicrobial hand sanitizers available.\n"<<"-Store and handle COVID-19 vaccines under proper conditions, including maintaining cold chain conditions and chain of custody at all times in accordance with a EUA or vaccine package insert, manufacturer guidance, and CDC guidance in the Vaccine Storage and Handling Toolkit."<<endl;
cout<<"-Appropriate security provisions to ensure no unauthorized access to vaccine doses."<<endl;
cout<<"\nAre all requirement met? \n1:Yes \n0:No"<<endl;
cin>>rq;
if(rq == 1)
{
cout<<"\nWhere is the location : "<<endl;
cin>>A.AddressName[i];
cout<<"How many vaccines required : "<<endl;
cin>>A.numVaccine[i];
cout<<"How many vaccine stall can a site hold : "<<endl;
cin>>A.numStall[i];
cin.ignore();
cout<<"Date for vaccine to be distributed"<<endl;
getline(cin,A.DateVax[i]);
cin.ignore();
cout<<"Enter your management contact number : "<<endl;
getline(cin,A.ContNum[i]);
cout<<"Certificate for "<<A.NameSite[i]<<endl;
i++;
}
else
{
cout<<"Thanks for the thought. We hope to cooperate with "<<(A.NameSite[i])<<" in the near future\n\n"<<endl;
if(i>0)
{
i = i-1;
}
else
{
i = 0;
}
}
return i;
}
void EditData(int i,struct Deets A)
{
int c,EN,edit=0;
for (int c=0;c<i;c++) //showing all Company/Institute name data
{
cout << c+1 << ". "<<A.NameSite[c]<<endl;
}
cout << "Enter number you would like to edit : "; //asking user to enter which data user want to edit
cin >> EN; //user enter which data they want to edit
c=EN-1;
cout << A.NameSite[c] << "\n" << "Do you want to edit this data? Yes:1 No:0"<<endl; //asking user whether they want to edit Company/Institute name
cin >> edit;
if(edit ==1) //if true, it will change the data
cin >> A.NameSite[c];
cout <<"Total stall : "<< A.numStall[c] << "\n" << "Do you want to edit this data? Yes:1 No:0"<<endl; //asking user whether they want to edit total Company/Institute vaccine stall
cin >> edit;
if(edit ==1) //if true, it will change the data
cin >> A.numStall[c];
cout <<"Adress : " << A.AddressName[c] << "\n" << "Do you want to edit this data? Yes:1 No:0"<<endl; //asking user whether they want to edit Company/Institute's address
cin >> edit;
if(edit ==1) //if true, it will change the data
cin >> A.AddressName[c];
cout << "Contact number : " << A.ContNum[c] << "\n" << "Do you want to edit this data? Yes:1 No:0"<<endl; //asking user whether they want to edit Company/Institute's contact number
cin >> edit;
if(edit ==1) //if true, it will change the data
cin >> A.ContNum[c];
cout << "Total Vaccine : "<< A.numVaccine[c] << "\n" << "Do you want to edit this data? Yes:1 No:0"<<endl; //asking user whether they want to edit total Company/Institute vaccine needed
cin >> edit;
if(edit ==1) //if true, it will change the data
cin >> A.numVaccine[c];
cout << "Date of vaccine : "<< A.DateVax[c]<< "\n" << "Do you want to edit this data? Yes:1 No:0"<<endl; //asking user whether they want to edit Company/Institute's receiving vaccine date
cin >> edit;
if(edit ==1) //if true, it will change the data
cin >> A.DateVax[c];
}
void ShowExisting(int i, struct Deets A) // void of ShowExisting that show the existing data stored in the program
{
for(int c=0; c<i; c++) //array to show all the existing data in the program so far
{
cout << (c+1) << ". "<< endl; //number that show the count of which set of data shown
cout << "Site Name: " << A.NameSite[c] << endl; //show the name of site in appropriate array of turn c
cout << "Address: " << A.AddressName[c] << endl; //show the address of site in appropriate array of turn c
cout << "Amount Vaccine: " << A.numVaccine[c]<< endl; //show the amount of vaccine needed in site in appropriate array of turn c
cout << "Amount Stall: " << A.numStall[c] << endl; //show the amount of stall needed in appropriate array of turn c
cout << "Vaccination Date: " << A.DateVax[c] << endl; //show the vaccination date in appropriate array of turn c
cout << "Contact Num.: " << A.ContNum[c] << "\n" << endl; //show the contact number of the reprsentative from the site in appropriate array of turn c
}
}
The program runs until input when there is no data in the file but when there is data, the program wont even go past
for(int c=0;c<=i;c++)
while(a>>V.NameSite[c]>>V.AddressName[c]>>V.numVaccine[c]>>V.numStall[c]>>V.DateVax[c]>>V.ContNum[c]);
please help as my caffeine brain is fried
*After considering everyone's response ive decided to rework the basis of the program with what everyone taught, Thank you for those who responded
IMHO, I would rewrite/redesign your code rather than debug it.
Let's start by differentiating a single Deet from a container of Deet:
struct Deet
{
string NameSite;
string AddressName;
int numVaccine;
int numStall;
string DateVax;
string ContNum;
};
You can then overload operator>>:
struct Deet
{
//...
friend std::istream& operator>>(std::istream& input, Deet& d);
};
std::istream& operator>>(std::istream& input, Deet& d)
{
std::getline(input, d.NameSite);
std::getline(input, d.AddressName);
input >> d.numVaccine;
input >> d.numStall;
std::getline(input, d.DateVax);
std::getline(input, d.ContNum);
return input;
}
You could declare a container and input the container like so:
std::vector<Deet> deet_container;
Deet d;
while (input_file >> d)
{
deet_container.push_back(d);
}
BTW, you should always put descriptive variables inside your function declarations. This gives people a better understanding of what the variables are and their positions.
Your function declarations could change:
typedef std::vector<Deet> Deet_Vector;
int AddData(int, Deet_Vector& V);
void EditData(int, Deet_Vector& V);
void ShowExisting(int, Deet_Vector& V);
void ClearArr(int, Deet_Vector& V);
By looking at AddData, the usage of the int first parameter is ambiguous.
Are you adding an int to the container?
Is the int the quantities of items to add to the container?
Likewise with the other functions.
Next, I would add one function at a time to the program, compile and debug, then add another, repeat.
BTW, you can simplify your Outputmenu function:
void Outputmenu()
{
static const char menu_text[] =
" -hello there!-\n"
"===========================================================\n"
" ***PLEASE CHOOSE ONE OF THE OPTION BELOW***\n"
"===========================================================\n"
"\t1. Add Data (about Vaccination Center)\n"
"\t2. Edit Data\n"
"\t3. Show Existing Data\n"
"\t0. Close Program\n"
"============================================================\n"
;
std::cout.write(menu_text, sizeof(menu_text);
}
By using the write method, the text is written as a block and is usually a lot faster than using a lot of operator<<.

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.

Conditional cin giving stacked cout messages

Using C++ (g++-4.7 on Mint 16).
Code is a unrefined (and unfinished) Tic-Tac-Toe game.
#include <iostream>
using namespace std;
int main()
{
//initial data
char turn='A';
char ttt[] = {'1','2','3','4','5','6','7','8','9'};
int move;
int over=0; //0 is no, 1 is yes
int valid=0;
while ( over == 0)
{
//display
cout << "\n" << ttt[0] << "|" << ttt[1] << "|" << ttt[2] <<"\n-----\n";
cout << ttt[3] << "|" << ttt[4] << "|" << ttt[5] <<"\n-----\n";
cout << ttt[6] << "|" << ttt[7] << "|" << ttt[8] <<"\n\n Choose a number (Player " << turn << "):";
//ask enter for play with turn
cin >> move;
cout << "\n";
valid = 0;
while (valid == 0)
{
//check if input is valid
if (((move > 0) and (move < 10)) and
((ttt[move-1] != 'A') and (ttt[move-1] != 'B')) and
(cin))
{
ttt[move-1] = turn;
valid=1;
}
else
{
cout << "Invalid slot. Choose a number (Player " << turn << "):";
cin >> move;
cout << "\n";
}
}
//check if done if no //change turn then goto //display
if (((ttt[0]==ttt[1]) and (ttt[1]==ttt[2])) or
((ttt[3]==ttt[4]) and (ttt[4]==ttt[5])) or
((ttt[6]==ttt[7]) and (ttt[7]==ttt[8])) or
((ttt[0]==ttt[3]) and (ttt[3]==ttt[6])) or
((ttt[1]==ttt[4]) and (ttt[4]==ttt[7])) or
((ttt[2]==ttt[5]) and (ttt[5]==ttt[8])) or
((ttt[0]==ttt[4]) and (ttt[4]==ttt[8]))or
((ttt[2]==ttt[4]) and (ttt[4]==ttt[6])))
{
//display winner or say draw
cout << "Player " << turn << " wins!\n";
over=1;
}
else
{
//change turn
if (turn=='A')
{ turn='B';
}
else
{ turn='A';
}
}
}
return 0;
}
There seem to be a bug on the code. On the part where check if input is valid the and (cin) seem to be failing.
When entering a character, (Instead of a number) it output continuously stacks of:
Invalid slot. Choose a number (Player A or B):
I tested the rest of condition without it, it was all working well. Is there a problem on the code or is this really "cin" problem? I've also tried out !(!cin) but it's the same scenario.
You must clear the fail bit from the cin stream in your else block.
When you enter a character that isn't an integer, the cin stream sets the fail bit, which you correctly check for in your if statement, but you never clear it afterward. This causes your input validity check to be false forever.
#include <limits>
...
else
{
cin.clear(); // Add this line
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // And this one
cout << "Invalid slot. Choose a number (Player " << turn << "):";
cin >> move;
cout << "\n";
}
For additional information, see the documentation for std::basic_ios::clear
Update: see this question and this question for similar problems.
Essentially, you also need to tell cin to ignore whatever is in the stream or it will continually set the fail bit with its bad contents you haven't cleared yet. I modified the above snippet to work.

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.

Sending the return vale to an array in c++

Here is the deal guys:
I'm making a stat generator. The program has a menu(not fully developed in this program, but I have previous code that will work)It asks for a name and then stores it to Character1.
Then it prompts that it is generating your scores.The function GenerateScore() takes 3 random numbers with the range 1-6 each, adds them together and returns the sum.
I want this to loop 6 times and store total into the array Stats[6].
Then I am sending the Character1 and the array to the txt file called charactersave.txt.
It saves whatever name I input each time but I get this when I open the txt file. I get this
anthony-858993460-858993460-858993460-858993460-858993460-858993460-858993460-117763858413957408144036511139574241439271911568132815670376-1177638760
Any help on this would be greatly appreciated,
#include <iostream>
#include <cstring>
#include <array>
#include <string>
#include <fstream>
using namespace std;
int GenerateScore();
int main()
{
int Stats[6];
char Selection;
string Character1;
int i;
cout << "Hello, welcome to my character generator. Please select an option" << endl;// Menu Options
cout << "A: Create Character Name and generate stats" << endl;
cout << "B: Display Name and Stats" << endl;
cout << "C: Quit" << endl;
cin >> Selection; // Menu Selection
cout << endl;
do
{
if ( (Selection == 'a') || (Selection == 'A') )// if user selects a, this happens
{
cout << "Welcome, Before you can start your adventures you must name your character." << endl;
cout << "Please enter your a name." << endl;// prompts user to enter a name for their Caracter
cin >> Character1;
cout << "Thank you now lets generate your stats." << endl;
for (i=0; i<6;i++)// I Want this to run the function GenerateScore() 6 times and input each result into the next element of Stats[6]
{
GenerateScore()>> Stats[i];
}
ofstream savecharinfo("charactersave.txt");// saves the Name and the filled array Stats[6] to the charactersave.txt file
if(savecharinfo.is_open())
{
savecharinfo << Character1;
for(int i = 0; Stats[i]; i++)
{
savecharinfo << Stats[i]; //writing numbers of values2 in the file
}
}
else cout << "File could not be opened." << endl;
break;// this is unfinished after this point
}
}
while ( (Selection != 'c') || (Selection == 'C') ); // ends the program if c or C is entered.
system("PAUSE");
return 0;
}
int GenerateScore()
{
int roll1 = rand()%6+2;
int roll2 = rand()%6+2;
int roll3 = rand()%6+2;
int sum;
sum=roll1+roll2+roll3;
return sum;
}
>> can only be used for std::ostream to achieve streaming behavior.
Change
GenerateScore()>> Stats[i];
to
Stats[i] = GenerateScore();