Adding to a struct from inside a loop in C++ - 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....

Related

How to introduce values in an array of structs? (c++)

I want to make a program that lets the user input the brand, price and color of a car for an unknown amount of cars, and cant figure out how to do that or what i have to search for in order to understand.
Example of what i want it to do: i want 20 cars, and i want to input values for each one of them and at the end have the program say which brand is the most expensive.
#include <iostream>
using namespace std;
struct car{
char brand[50];
char color[60];
unsigned short int price;
};
void compare(car a, car b){
if(a.price > b.price)
cout << "Most expensive: " << a.brand;
else
cout << "Most expensive: " << b.brand;
}
int main()
{
car m1, m2;
cout << "Brand of first car: "; cin >> m1.brand; cout << endl;
cout << "Color of first car: "; cin >> m1.color; cout << endl;
cout << "Price of first car: "; cin >> m1.price; cout << endl << endl;
cout << "Brand of second car: "; cin >> m2.brand; cout << endl;
cout << "Color of second car: "; cin >> m2.color; cout << endl;
cout << "Price of second car: "; cin >> m2.price; cout << endl << endl;
compare(m1, m2);
return 0;
}
Your first step will be:
int main()
{
car m[20]; // todo better: std::vector
for(int i=0; i < 20; i++)
{
cout << "Brand of first car: "; cin >> m[i].brand; cout << endl;
cout << "Color of first car: "; cin >> m[i].color; cout << endl;
cout << "Price of first car: "; cin >> m[i].price; cout << endl << endl;
}
}
The next step will be to do something with m[].
If you create your object (of type car) named m1, m2 and then you would like to add some values to its' fields, you have to create the object dynamically, so it will be:
car *m1 = new car;
cin >> m1->brand;
I'm more into Java right now, so I'm not 100% sure about the syntax, but the concept seems right. Hope it works! ;-)

My program is not correctly outputting the amount of students in my struct

i am making a program which is supposed to collect input from the user by asking for id, name, units attempted, units earned and the gpa of a student and store that into a struct. Currently, when i input more than one student into the struct, it only outputs the last student in the array. What can i do to fix this?
Here is my code
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Student {
string ID; //an 8-digit student ID
string name; //name of the student
unsigned unitsAttempted;//number of units attempted by the student
unsigned unitsEarned; //number of units earned by the student
double gpa; //the grade point average for the student
};
int main()
{
Student students[10];//array for 10 Student Structs
char answer = 'y';
int number = 0;
while ((answer == 'y') || (answer == 'Y')) {
//prompt the user to enter the data
{
answer = ' ';
int i = 0;
cout << "Enter the students ID: \n" ;
getline(cin, students[i].ID);
cout << "\nEnter the name:\n";
getline(cin, students[i].name);
cout << "\nEnter the units attempted:\n";
cin >> students[i].unitsAttempted;
cin.ignore();
cout << "\nEnter the units earned:\n";
cin >> students[i].unitsEarned;
cin.ignore();
cout << "\nEnter the GPA: \n";
cin >> students[i].gpa;
cin.ignore();
cout << "\nWould you like to add another student? y or n\n";
cin >> answer;
cin.ignore();
i++;
number++;
}
}
cout << left << setw(10) << "ID " << setw(20) <<"Name" << setw(20) <<"Units Attempted" << setw(20) <<"Units Earned" << setw(10) <<"GPA";
cout << "\n===============================================================\n";
for (int i = 0; i < number; i++)//display the students
{
cout << left << setw(10) << students[i].ID << setw(20) << students[i].name << setw(20) <<students[i].unitsAttempted << setw(20) <<students[i].unitsEarned << setw(10) <<students[i].gpa << endl << endl;
}
return 0;
}
Im still learning so please go easy on me, thanks.
Currently, when i input more than one student into the struct, it only outputs the last student in the array.
It looks most likely that the scope of your i is incorrect:
int i = 0; //<-- this should be declared outside the `while` loop
As it stands, your i is scoped inside while loop, so it will be reset every time the while loop is entered. In other word, that i never increased.

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

Create an array that holds struct objects 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".

reading and printing inputs and C-string in C++

I have a simple program to read and echoed the user's input and calculate the total amount. I'm having trouble with arrays. I want to know how to use an array to read and print each product name and the cost and the find grand total upon checkout. Should I also use functions?
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
const int MAX_CHAR = 100;
void pause();
int main()
{
char productName[MAX_CHAR];
double price;
char reply;
double total = 0;
cout << fixed << showpoint << setprecision(2);
cout << "Welcome to your shopping calculator!" << endl;
do {
cout << "Enter the product name: ";
cin.get(productName, MAX_CHAR, '\n');
cin.ignore(100, '\n');
cout << "Enter the amount: $";
cin >> price;
while (!cin) {
cin.clear();
cin.ignore(100, '\n');
cout << "Invalid amount. Please enter the amount: $";
cin >> price;
}
cin.ignore(100, '\n');
cout << "The product name is" << " " << productName << " "
<< " and it costs" << " " << "$" << price << endl;
total += price;
cout << "The total amount is " << " " << total << endl; //program needs to keep a running total
cout << "Would you like to continue shopping? (y/n): ";
cin >> reply;
cin.ignore(100, '\n');
} while ( reply == 'Y' || reply == 'y'); //the program will continue until the user wants to checkout
pause();
return 0;
}
void pause()
{
char ch;
cout << "Press q followed by Enter key to continue....." << endl;
cin >> ch;
}
Thanks for the help!
You need to map the product name to the cost using std::map so that you can print the respective pairs afterwards. As for the grand total, that's stored in the variable total so printing it is trivial.
To do this, you will need to include the <map> header, as the Standard Library class std::map is defined there. Moreover, I've also included some changes to your code that should be considered. In particular, using std::string and using std::numeric_limits<...>::max() to return the constant.
#include <iostream>
#include <string>
#include <map>
int main()
{
std::string productName;
double price;
char reply;
double total = 0;
std::map<std::string, double> productToPrice;
std::cout << std::fixed << std::showpoint << std::setprecision(2);
std::cout << "Welcome to your shopping calculator!" << std::endl;
while ((std::cin >> reply) && (reply == 'y' || reply == 'Y'))
{
cout << "Enter the product name: ";
std::cin >> productName;
cout << "Enter the amount: $";
while (!(cin >> price))
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid amount. Please enter the amount: $";
}
total += price;
productToPrice.insert(std::make_pair(productName, price));
cout << "Would you like to continue shopping? (y/n): ";
}
...
}
Note the changes I made. Please use them.
To print you simply do:
typedef std::map<std::string, double>::const_iterator iter_type;
for (iter_type beg(productToPrice.begin()),
end(productToPrice.end()); beg != end; ++beg)
{
std::cout << beg.first << " -- " << beg.second << std::endl;
}
std::cout << "\nThe total price is: " << total;
You are definitely on the right track. I think you are mixing I/O conventions in C and C++ which is causing a lot of your issues. It would be very helpful if you could elaborate on what exactly your issues are.
Carpetfizz is correct in that since you don't know the number of items at compile time, you will need to use a dynamic array with std::vector. You can learn about vectors here.
In addition, C++ has a very useful string data type that you can include with #include <string>. Using this, as well as a junk string such as string junk;, you can avoid using cin.ignore(...) and get cleaner I/O by using getline(cin, junk).
I strongly recommend doing this because creating a vector of C-strings or C-style strings is a pain, because C-style strings are actually arrays of characters, so you'd have to use std::vector<std::vector<char> > products.