How to relay cin from main into fucntions and struct above main? - c++

ok so i need to figure out how to place the cin user entered in main into the function, and then from the function into the struct; im clueless on what i need to do in the main not just regarding the code but how it connects (memory wise) what is written into the main with the rest of the program. the #include must be ONLY iostream, vector ANDstring!
p.s at the end i need to print out the films stored in the vector of films
using namespace std;
struct Film
{
string Name;
double Length;
string Producer;
string Lead_Role;
string Type;
};
Film create_film()
{
Film f;
cout << "Enter the name of the movie: ";
getline(cin, f.Name);
cout << "Enter movie length: ";
cin >> f.Length;
cin.ignore;
cout << "Enter the producer: : ";
getline(cin, f.Producer);
cout << "Enter the lead role: ";
getline(cin, f.Lead_Role);
cout << "Enter movie type";
getline(cin, f.Type);
return f;
}
int main()
{
//here i need to figure it out
return 0;
}

I think (it's not completely clear) that you're just looking for
int main()
{
Film my_film = create_film();
// do something with my_film
...
return 0;
}
The way I've used create_file() in main is called a function call. It's how you 'connect' one function to another, though 'transfer control' is probably a better way of saying it. When you call a function control transfers from the calling function (main in this case) to the called function (create_film in this case). When the called function returns control goes back to the calling function. And of course when the main function returns the program terminates.

Related

Asking for conditional information in C++

Not sure how I was supposed to formulate the title.
I'm writing a program that asks for a students name, and if the name is not "stop", then it asks for a course name. If the course name is not "stop", it asks for a grade, then returns to ask for another course until the course name is "stop". Then it asks for another student and does the whole thing again until the student name is "stop". Then it prints all the students with their courses and grades.
Here is my code:
#include <iostream>
#include <vector>
using namespace std;
struct student{
public:
string name;
string course;
int grade;
}student_t;
void input(){
cout << "Please type the name of a student: " << endl;
getline(cin, student_t.name[i]);
if (student_t.name.compare("stop")){
break;
}
else {
cout << "Please type a course name: " << endl;
getline(cin, student_t.course);
if (student_t.course.compare("stop")) {
break;
}
else {
cout << "Please type the grade: " << endl;
cin >> student_t.grade;
}
}
}
int main() {
int i;
vector<student> input(i);
for (i = 0; i < 20; ++i){
student[i].input();
}
cout << student_t.name << " - " << student_t.course << " - " << student_t.grade << endl;
return 0;
}
It does not work at all..
I'm new to C++ so I dont really know why.
Any ideas?
I can give one or two recommendations.
Instead of checking if every step is wrong (i.e. equals "stop"), focus on what is right (i.e. what's the next things to read). From a mental perspective, I find it much easier to think about what has to be right for the program to progress as intended, as opposed to "What can go wrong here?" at every step. Your input() could then be (in pseudo code):
if (student_t.name is not "stop")
{
Read_course_name();
if (student_t.course is not "stop")
{
Read_grades();
// Done
return(StudentInfo);
}
}
// Ending up here means "stop" was typed so deal with that
// in a meaningful way
...
Take a look at https://en.wikipedia.org/wiki/Separation_of_concerns and then ask yourself, -Is the input() function really an input or are there more than one concern that coud be broken out in a separate function?
Cheers
/N

How to Create multiple classes in C++?

Create 200 classes (think about an efficient way to do this), each class will contain the following public members:
a. Name - Which will hold first and last name
b. Address- which will hold the street number and name
c. Phone - which will hold the phone number
The user will be able to enter the information for between 1 and 200 individuals(determined by the user).
#include<iostream>
#include<string>
using namespace std;
class information {
public:
//member variables go here
};
int main() {
char answer = 'Y';
int i = 0; //why is this here?
//instantiate your classes here
do {
cout << "This is the address book enter the first and last name "
<< "address and phone number: \n";
cout << "Name (First and Last): ";
//will need a 'cin' to store the name (hint: use getline)
cout << "\n\nAddress: ";
//address
cout << "\n\nPhone Number: ";
//phone
i++;
cout << "Enter another person? Y/N: ";
//answer Y or N
} while ;
system("pause");
return 0;
}
class information {
public:
//member variables go here
string name, address,phone;
};
And in the main method, write
information info[200];
This creates 200 objects of class information. To set values, you need to run a loop like:
for(i=0;i<200;i++)
{
cin>>info[i].name>>info[i].address>>info[i].phone;
}

Calling Main replaces vector object and overwrites data

I am learning c++ and I can't wrap my head around this problem. I have created a class object which hold information of a vehicle. And the class name is vehicle. Here is the class:
class vehicle {
private:
string vehicleNumber;
int vehicleType;
public:
//Default Constructor
vehicle();
//Overload Constructor - #params<vehicleNumber, vehicleType>
vehicle(string vehicleNo, int type){
vehicleNumber = vehicleNo;
vehicleType = type;
}
//Some stuff to test
string getNo(){
return vehicleNumber;
}
int getType(){
return vehicleType;
}
};
And now in my main I have a void method which then takes in user input and puts the object in a vector. So in my main:
//Ref
void storeVehicle(vector<vehicle>&);
void storeVehicle(vector<vehicle>& createNewVehicle){
string number;
int type;
cout << "Enter Vehicle Number: ";
cin >> number;
cout << "Enter the vehicle type: ";
cin >> type;
vehicle newV(number, type);
createNewVehicle.push_back(newV);
cout << endl;
}
//
Now here is the problem I am facing. Inside of my main method, I am creating the object. And this works perfectly find except if I call the main method again, it initializes the object again and I loose my previous data. I am not sure how to tackle this.
Here is the main method:
int main(){
vector<vehicle> newVehicle;
storeVehicle(newVehicle);
return main();
}
So here I am returning main() again so that it reruns. But when it does, i loose my previous vector which held the data. Now how can I keep the data and keep calling the storeVehicle method?
Edit
I also have a switch case which I am using to determine what the user chooses as an option. It may be to display the vehicle information or it maybe to add a new vehicle. In this case too, how can I add the vehicle without loosing previous data. Here is my switch which is inside another method:
void mainMenu(){
int option;
cin >> option;
switch(option){
case 1: {
vector<vehicle> newVehicle;
storeVehicle(newVehicle);
break;
}
default:
cout << "Wrong option";
}
}
So now in my main method, I am simply calling this switch method. Either way, I loose the data yes?
EDIT
I don't understand why people keep downvoting. Aren't we all here to learn? And yet I get a downvote. Sooner or later, stackoverflow decides to block me from asking questions.
Main isn't intended to be used like that, it's just an entry point for your application.
For what you're looking to do, you would be interested in looping. This way a certain section of your code can be ran repeatedly until a condition is met.
int main(){
vector<vehicle> newVehicle;
while(true)
{
storeVehicle(newVehicle);
}
return 0;
}
Take a look at how different loop types work. https://www.tutorialspoint.com/cplusplus/cpp_loop_types.htm
Also, the one in my example is an infinite loop, since the condition is always true.
EDIT The question was changed.
The problem is that each time you call the mainMenu function that the vector is recreated. Create the vector in your Main function and then pass it by ref into the mainMenu function, so that it can then be passed into your storeVehicle function.
int main()
{
vector<vehicle> newVehicle;
while (true)
{
mainMenu(newVehicle);
}
return 0;
}
void mainMenu(vector<vehicle>& createNewVehicle) {
int option;
cin >> option;
switch (option) {
case 1: {
storeVehicle(createNewVehicle);
break;
}
default:
cout << "Wrong option";
}
}
You'd have to add a header for this function to work.
#include <limits>
void storeVehicle(vector<vehicle>& createNewVehicle) {
string number;
int type;
cout << "Enter Vehicle Number: ";
cin >> number;
cout << "Enter the vehicle type: ";
cin >> type;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
vehicle newV(number, type);
createNewVehicle.push_back(newV);
cout << endl;
}

How to display the name from the array name?

I'm trying to study c++ about array
and I'm having a problem displaying the name from the array name
Because when I try to display the name of the passenger based on where he seat
the first letter becomes the last letter of his name..ahmm
Here's my code
#include <iostream.h>
#include <conio.h>
char* name[10]={" "};
int* seat=0;
char* pname="The Passenger is: ";
char ask;
void display();
int main()
{
clrscr();
cout<<"The Entering of name and seat number..."<<endl;
do
{
cout<<"\nEnter your name: ";
cin>>*name;
cout<<"Enter your seat number: ";
cin>>*seat;
cout<<"Do you want to input again?(Y/N): ";
cin>>ask;
}
while(ask=='y'||ask=='Y');
cout<<"\nDo you want to see the passenger's name?(Y/N): ";
cin>>ask;
if(ask=='y'||ask=='Y')
{
cout<<"\nThe Program will now direct you to the displaying of passenger's name...."<<endl;
display();
}
else
{
cout<<"\n\nThe Program will end shortly....";
}
getch();
return 0;
}
void display()
{
do
{
cout<<"\nEnter seat number to display passenger's name: ";
cin>>*seat;
cout<<pname<<*name[*seat-1]<<endl;
cout<<"Do you want to try again?(Y/N): ";
cin>>ask;
}
while(ask=='y'||ask=='Y');
cout<<"\nThe Program will now end shortly....";
getch();
}
To display the name from the array name you have at first to define the array correctly.:)
If you do not know yet about standard class std::string then the array should be defined as for example
char name[10][20];
that is it can store 10 names that have length no more than 20 characters.
Or if you know about class std:string then you can define it as
#include <string>
std::string name[10];
And it would be even better to define
#include <string>
#include <array>
std::array<std::string, 10> name;
For this program neither pointer is needed to be defined.
Take into account that when you ask to enter a seat number you should check that this number is in the range 1 - 10 (in this case you will need to decrease it by one when will use it to access the array) or 0 - 9.
You seem to be having a problem with pointers. Namely
int* seat=0;
will not allocate space for the integer, but instead allocate space for a pointer and then set this pointer and set it to address 0. When you perform
cin>>*seat;
Your program attempts to dereference the pointer which does not point to anything. Furthermore when you perform
cin >>*name
You are not writing to the whole string but instead writing to the dereference location, namely the first character of the string.
For a start change
int* seat=0;
to
int seat = 0
and
cin>>*name;
to
cin>>name;
good luck!
Edit:
also you want to change the:
cin >> *seat;
to
cin >> seat
Nevertheless you might need some more practice in the basic language features, like pointers, you could use some existing data structures. Since you are using cout and cin i assume your compiler supports the C++ standard library. I would use a map, to save the passengers.
#include <iostream>
#include <map>
struct passenger
{
char name[10];
};
std::map<int, passenger> passengers;
int seat;
char ask;
void display();
int main()
{
std::cout<< "The Entering of name and seat number..." << std::endl;
do
{
passenger p;
std::cout << "\nEnter your name: ";
std::cin >> p.name;
std::cout << "Enter your seat number: ";
std::cin >> seat;
// add passenger to the map
passengers.insert(std::pair<int, passenger>(seat, p));
std::cout << "Do you want to input again?(Y/N): ";
std::cin >> ask;
}
while(ask=='y'||ask=='Y');
std::cout << "\nDo you want to see the passenger's name?(Y/N): ";
std::cin >> ask;
if(ask=='y' || ask=='Y')
{
std::cout << "\nThe Program will now direct you to the displaying of passenger's name...." << std::endl;
display();
}
return 0;
}
void display()
{
do
{
std::cout << "\nEnter seat number to display passenger's name: ";
std::cin >> seat;
// check if passenger data is available for this seat
if(passengers.find(seat) != passengers.end()) {
std::cout << "The Passenger is: " << passengers[seat].name << std::endl;
} else {
std::cout << "Seat still available ..." << std::endl;
}
std::cout << "Do you want to try again?(Y/N): ";
std::cin >> ask;
}
while(ask=='y' || ask=='Y');
}
If you are using a pointer *seat you don't have to access it as
cin>>*seat. You only need to write cin>>seat.
While you are learning cpp, check out what pointers are too.
Here's a little info on that too, though that is not exactly the subject matter,
int *S; // pointer of type int
int x; // variable of type int
S = &x; // pointer S is now pointing to memory location of x
S = 4;
OR
x = 4; // changes the contents of memory location to which S points`
cout << *S; // displays the memory address to which S points i.e.
x

functions not returning values that a user enters

I AM working on this program for an assignment, so I don't want the answer...just a push in the right direction.
I have written a program in which a user will input a 3-digit ID (required) and an amout of KWh used for the month. After that criteria has been entered, it will print out a short summary + the charges for that month per user. And this is enclosed in a loop to ask if there are any more IDs to be entered.
Below is my opening code and loop structure:
#include <iostream>
#include <string>
#include <iomanip>
#include <windows.h>
using namespace std;
//function prototypes
string get_user_ID();
int get_cust_kwh();
string display_cust_data();
int main()
{
string userID;
int userKWH;
char answer;
while ((answer !='N')&&(answer !='n')){
userID = get_user_ID();
userKWH =get_cust_kwh();
display_cust_data();
cout << "\n\nWould you like to add another utility ID? : (Y or N)";
cin >> answer;
}
}
system("pause")
return 0;
I can get the loop to function correctly, but my functions don't seem to be returning the values that the user enters. As I am new to functions, I am sure it's some silly mistake, but one that has been driving me crazy. Here are the functions:
**********function definitions**********
string get_user_ID(){
string usrID;
cout << "\n\nPlease enter in your 3-digit utility ID: ";
cin >> usrID;
return usrID;
}
int get_cust_kwh(){
int usrKWHs;
cout << "Please enter the total KWH used for the month: ";
cin >> usrKWHs;
return usrKWHs;
}
string display_cust_data(){
string usrID;
int usrKWHs;
double userCharge;
cout << "\n\nUSER ID KWHours Charge($)\n";
cout << fixed << setprecision(2);
cout << usrID << " " << usrKWHs << " " << userCharge << endl;
}
I'm thinking something to do with the way the variables in the functions are used.
Thanks for any pushes you can give!
The problem is display_cust_data() doesn't know about variables in main function scope. What you are printing is just the local variables which has garbage values.
string display_cust_data(){
string usrID; // This is a different variable and is not equivalent to the
// variable in main.
Also why the function's return type is string ?
Look at your display_cust_data. How does it get any information about what to display?
You need to find a way to pass the user input variables to your display function. The variables you have in the display_cust_data() function are newly created there and are not the same as the variables you have in your while loop in your main() function. All of the variables you display in that function are uninitialised and so you have no idea what their values will actually be. Consider adding arguments to the function so that when you call it you can pass the user input variables to it so that you can display the values you want to display.