Create an array that holds struct objects C++ - c++

I am a novice programmer and I am creating a program that holds several objects of a struct type. The program needs to accept user input but I don't know how to do it. First, here's the code I'm using to define the struct:
struct Apartment{
int number;
string owner;
string condition;
}ap;
And here's the code I'm using to ask for user input:
cout << "Enter the apartment number: " << endl;
cin >> ap.number;
cout << "Enter the name of the owner: " << endl;
cin >> ap.owner;
cout << "Enter the condition: " << endl;
cin >> ap.condition;
apartment building[50] = { ap.number, ap.owner, ap.condition};
The last line of code is how I am trying to save the object in an array, bu I don't know if it works.
I later need to print all the objects, so it would be nice if you helped me with that too. I am using Visual Studio 2013 as a compiler, in case it makes any difference.

First of all, let's understand what you are doing.
struct Apartment{
int number;
string owner;
string condition;
}ap;
Firstly, you create an Apartement struct which have the name "ap".
cout << "Enter the apartment number: " << endl;
cin >> ap.number;
cout << "Enter the name of the owner: " << endl;
cin >> ap.owner;
cout << "Enter the condition: " << endl;
cin >> ap.condition;
Secondly, (I assume that you are in your main function) you are asking the user to enter some information. You have to keep in mind that cin only that the first word and stop at the first whitespace it sees if you plan to save more word, you should use getline. See this link for more information : http://www.cplusplus.com/doc/tutorial/basic_io/
apartment building[50] = { ap.number, ap.owner, ap.condition};
Finally, your last line will crash for two reasons. Firstly, because the type apartment does not exist. I believe you meant to write Apartment. Secondly because you cannot create an array like this. I suggest you to look at this: http://www.cplusplus.com/doc/tutorial/arrays/
I am not sure exactly what you want to do, so I will give you a sample of code that ask a user how many apartment he has and ask the information for the number of apartment he owns.
struct Apartment{
int number;
string owner;
string condition;
};
int main() {
cout << "Hello, how many apartment do you own?";
int nbAppt = 0;
cin >> nbAppt;
Apartment appt[nbAppt];
for(int i = 0; i < nbAppt; i++) {
cout << "Appartment number " << i << endl;
cout << "Enter the apartment number: ";
cin >> appt[i].number;
cout << "Enter the name of the owner: ";
cin >> appt[i].owner;
cout << "Enter the condition: " << endl;
cin >> appt[i].condition;
}
}
Ps: Please note that I assumed that you included namespace std;
Ps2: I did not include any relevant include.

struct Apartment{
int number;
string owner;
string condition;
}ap;
void AddApartment(vector<Apartment> &vtnew)
{
Apartment building;
cout << "Enter the apartment number: " << endl;
cin >> building.number;
cout << "Enter the name of the owner: " << endl;
cin >> building.owner;
cout << "Enter the condition: " << endl;
cin >> building.condition;
vtnew.push_back(building);
}
void DisplayApt(vector<Apartment> vtnew)
{
vector<Apartment> ::iterator it;
for (it = vtnew.begin(); it != vtnew.end(); it++)
{
cout << "apartment number" <<it->number;
cout << "name of the owner" << it->owner;
cout << "condition" << it->condition;
}
}
int main()
{
vector<Apartment> vt;
AddApartment(vt);
AddApartment(vt);
AddApartment(vt);
DisplayApt(vt);
return 0;
}
What you are doing in your code is to declare an array for apartment to hold 50 apartments, but when you are using vectors we need not to give the count beforehand, we can keep adding the apartments, without worrying about the size!

I think you have a confuse here.
Apartment building[50]
means that this is an array of 50 elements and each element is a struct with type Apartment.
For example, it should be like this:
struct Apartment obj1;
struct Apartment obj2;
struct Apartment obj3;
Apartment building[3] = {obj1, obj2, obj3};
And I wonder what is the main purpose of "save object in an array" ?
Every element of an array should have same datatype and every field of a struct may not have same datatype, so that you shouldn't "save object in an array".

Related

Using a struct to hold information entered by the user C++

Okay, so I am writing a C++ program to declare a struct data type that holds the following information on an employee (First Name, Last Name, ID, Pay Rate, and Hours). My problem is that the user can only enter in the ID and First Name, then the whole program runs without letting the user enter the rest of the data.
Heres my code:
#include <iostream>
#include <iomanip>
using namespace std;
struct Employee
{
int employeeID;
char firstName;
char lastName;
float payRate;
int hours;
};
int main()
{
int i, j;
cout << "How Many Employees Do You Wish To Enter?:\n\n";
cin >> j;
Employee info;
for (i = 0; i < j; i++)
{
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << setw(5) << "\n Please Enter The Employee ID Number: ";
cin >> info.employeeID;
cout << setw(5) << "\n Please Enter Employees First Name: ";
cin >> info.firstName;
cout << setw(5) << "\n Please Enter Employees Last Name: ";
cin >> info.lastName;
cout << setw(5) << "\n Please Enter Employees Pay Rate: ";
cin >> info.payRate;
cout << setw(5) << "\n Please Enter The Hours The Employee Worked:
";
cin >> info.hours;
}
cout << "\n\n \n";
cout << "ID" << setw(15) << "First Name" << setw(10) << "Last Name" <<
setw(10) << "Pay Rate" << setw(10) << "Hours";
cout << endl;
for (i = 0; i < j; i++)
{
cout << "\n" << info.employeeID << setw(15) << info.firstName << setw(10) << info.lastName << setw(10) << info.payRate << setw(10) << info.hours;
}
cout << "\n\n \n";
system("pause");
return 0;
};
#include <iostream>
#include <iomanip>
#include <string> //Allows you to use strings, which are way more handy for text manipulation
#include <vector> //Allows you to use vector which are meant to be rezied dynamicaly, which is your case
using namespace std;
struct Employee
{
int employeeID;
string firstName; //HERE : use string instead of char (string are array of char)
string lastName; //HERE : use string instead of char
float payRate;
int hours;
};
int main()
{
int j;
cout << "How Many Employees Do You Wish To Enter?:\n\n";
cin >> j;
vector<struct Employee> info; //creation of the vector (dynamic array) to store the employee info the user is going to give you
for (int i = 0; i < j; i++) //declare your looping iterator "i" here, you will avoid many error
{
struct Employee employee_i; // create an employee at each iteration to associate the current info
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << "\n Please Enter The Employee ID Number: ";
cin >> employee_i.employeeID;
cout << "\n Please Enter Employees First Name: ";
cin >> employee_i.firstName;
cout << "\n Please Enter Employees Last Name: ";
cin >> employee_i.lastName;
cout << "\n Please Enter Employees Pay Rate: ";
cin >> employee_i.payRate;
cout << "\n Please Enter The Hours The Employee Worked: ";
cin >> employee_i.hours;
info.push_back(employee_i); //store that employee info into your vector. Push_back() methods expands the vector size by 1 each time, to be able to put your item in it
} // because you employee variable was create IN the loop, he will be destruct here, but not the vector which was created outside
cout << "\n\n \n";
for (int i = 0; i < j; i++) //the loop to get back all the info from the vector
{
cout << "ID :" << info[i].employeeID << " First Name :" << info[i].firstName << " Last Name :" <<
info[i].lastName << " Pay Rate :" << info[i].payRate << " Hours :"<< info[i].hours;
cout << endl;
//notice the info[i], which leads you to the employee you need and the ".hours" which leads to the hours info of that specific employee
}
system("pause");
return 0;
}
First, please read Tips and tricks for using C++ I/O (input/output). It might be helpful to understand C++ I/O.
Here are some comments on your code:
First
Use string instead of char.
struct Employee
{
int employeeID;
string firstName;
string lastName;
float payRate;
int hours;
};
Second
Use array of Employee object to store multiple employees.
Employee info[100];
Third
Use cin carefully depending data types. In your case, it would be something like this:
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << setw(5) << "\n Please Enter The Employee ID Number: ";
cin >> info[i].employeeID;
cin.ignore(); //It is placed to ignore new line character.
cout << setw(5) << "\n Please Enter Employees First Name: ";
getline (cin, info[i].firstName);
cout << setw(5) << "\n Please Enter Employees Last Name: ";
getline (cin, info[i].lastName);
cout << setw(5) << "\n Please Enter Employees Pay Rate: ";
cin >> info[i].payRate;
cout << setw(5) << "\n Please Enter The Hours The Employee Worked: ";
cin >> info[i].hours;
Fourth
std::getline() can run into problems when used before std::cin >> var. So, std::cin.ignore() can be used in this case to solve the problem.
I hope it helps.

C++ not able to type after cin >> answer;

I'm writing a basic program, similar to ELIZA(online therapist) simple questions and answers but I'm stuck at the end. after cin >> answer; I'm not able to write anything.
int main () {
short number;
string color;
string sport;
int answer;
string travel;
// Greets user
cout << "Hello, I'm Samantha" << endl;
// Asks user for their favorite sport
cout << "What's your favorite sport?";
cin >> sport;
cout << "I like " << sport << " too!" << endl;
cout << "How about your favorite color?";
cin >> color;
cout << "Not my favorite color but it's nice!" << endl;
cout << "Tell me something you've never told anyone before";
cin >> answer;
cout << "Don't worry, your secret is safe with me!" << endl;
cout << "Hows your life going?";
cin >> answer;
return 0;
}
your variable named "answer" has a data type integer. the first time you prompt the user to enter something from the console (apparently to be a string) the cin object attempts to initialize "answer" with a string (probably because the prompts does not ask for a number) which kills the cin object which will not allow the object to take instructions...so the next time you want to use it there is no cin object.
Just change the data type for "answer" to string.
Dr t

Is there a way to store date and time in a struct? C++

I need to store current date and time on a string to store it in a struct. I don't even know if that's possible, but I need to do it. I will try to further explain it:
I have this struct:
struct Apartment{
int number;
string owner;
string condition;
}ap
And this code to add a new object of the same struct:
cout << "Enter the apartment number: " << endl;
cin >> ap.number;
cout << "Enter the name of the owner: " << endl;
cin >> ap.owner;
cout << "Enter the condition: " << endl;
cin >> ap.condition;
And I need a variable for date and time. I need it to save the time and date the object was created. I don't know if I can do it with string or any other thing. I need it to be printable, too. I would be really thankful if you could help me.
You can use std::time_t, std::time() and std::ctime() like this:
#include <ctime>
#include <string>
#include <iostream>
struct Apartment
{
int number;
std::string owner;
std::string condition;
std::time_t when;
};
int main()
{
Apartment ap;
std::cout << "Enter the apartment number: " << std::endl;
std::cin >> ap.number;
std::cout << "Enter the name of the owner: " << std::endl;
std::cin >> ap.owner;
std::cout << "Enter the condition: " << std::endl;
std::cin >> ap.condition;
ap.when = std::time(0);// set the time to now
std::cout << "Record created on: " << std::ctime(&ap.when) << std::endl;
}

How to remove a struct element from a vector?

I'm a newbie programmer and I'm working on a program that holds a registry of pets in a hotel (some silly exercise we saw in class, doesn't matter). I'm using vectors for holding the struct elements (pets). The code for the struct is this:
struct Pets{
string Name;
string Race;
string Owner;
int Tel;
}p;
And the function to ask for user input is this:
AddPet(vector<Pets> &vtnew)
{
Pets newpet;
cout << "Enter the pet's name: " << endl;
cin >> newpet.Name;
cout << "Enter the pet's race: " << endl;
cin >> newpet.Race;
cout << "Enter the owner's name: " << endl;
cin >> newpet.Owner;
cout << "Enter the owner's telephone number: " << endl;
cin >> newpet.Tel;
vtnew.push_back(newpet);
}
Ok, now I need to create a function to remove the pet by entering the name or something. Is there any way to do that?
A vector is an unsorted container so the simple solutions are really your only choice.
void RemovePet(std::vector<Pet> & pets, std::string name) {
pets.erase(
std::remove_if(pets.begin(), pets.end(), [&](Pet const & pet) {
return pet.Name == name;
}),
pets.end());
}
This is known as the Erase-remove idiom.
Note that this will remove all pets matching that name, not just one.

Adding to a struct from inside a loop in C++

I'm sorry if there are other threads that ask this question, but I unfortunately don't understand enough C++ yet to understand most of them.
I'm trying to use a loop to ask the user a series of questions, and then save those responses in a struct.
struct custOrder
{
char fruitOrdered[20];
int qty;
double orderPrice;
double totalPrice;
};
string choice;
cout << "Do you want to purchase fruit (yes/no)? ";
cin >> choice;
cout << endl;
char order;
double orderQTY;
for (choice; choice == "yes"; choice)
{
cout << "Which fruit would you like?" << endl << endl;
cin >> order;
cout << endl;
cout << "How many pounds would you like?";
cin >> orderQTY;
custOrder order = //if for example they respond "apples" i want the resulting variable to be custOrder.apples
{
order,
orderQTY,
order.price,
orderQTY * order.price
};
cout << "Do you want to purchase another fruit? ";
cin >> choice;
cout << endl;
}
cout << "Thanks for your business." << endl;
I know this is basic stuff, but I am completely lost.
You use something like:
custOrder thisOrder;
thisOrder.order = order;
thisOrder.orderQTY = orderQTY;
so its really quite easy - you just access the members of a struct variable as variableName.member. Not sure about your structure type definition, I would be using:
typedef struct custOrder....