Call void function in IF statement C++ - c++

listSelectedDVD() should display the detail when i enter the title. but in my code Im able to enter the title but didn't display details.unable to pass-in argument.
#include <iostream>
#include <string>
using namespace std;
struct myStock // declare myStock fields
{
string title;
double price;
int stockLevel;
bool award;
};//end of strcut myStock
myStock list[5];
void initialize();
void listSelectedDVD(string);
int main()
{
int choice;
string enterTitle;
cout << "****** MAIN MENU ******" << endl;
cout << "1. List deatils of selected title" << endl;
cout << "4. Exit" << endl;
cout << endl;
cout << "enter your choice: " << endl;
cin >> choice;
if (choice == 1)
{
cout << "Enter a Title: " << endl;
cin >> enterTitle;
listSelectedDVD(enterTitle);
}
else if (choice == 4)
{
return 0;
}
system("PAUSE");
}//end of main
Here is my void Function of void initialize() & void listSelectedDVD(string enterTitle) ;
void initialize()
{
list[0].title = "Ilo Ilo";
list[0].price = 35.55;
list[0].stockLevel = 15;
list[0].award = true;
list[1].title = "Money Just Enough";
list[1].price = 10.35;
list[1].stockLevel = 0;
list[1].award = false;
}
void listSelectedDVD(string enterTitle)
{
for(int i=0;i<5;i++)
{
if (list[i].title.compare(enterTitle) == 0) //list[i].title == enterTitle
{
cout << "Title : " << list[i].title << endl;
cout << "Price : " << list[i].price << endl;
cout << "Stock : " << list[i].stockLevel << endl;
cout << "Award : " << list[i].award << endl;
}
else {
out<<"Invalid Title"<<endl;
//call back the main menu function//
}
}
}

You should first call initialize() from main before calling listSelectedDVD().
int main()
{
initialize();
//rest of your code
}//end of main

The main problem is, when you take the user input on this line "cin >> enterTitle;", it gets the first word you typed separated by space. So when you type
Money Just Enough
then the value of enterTitle just becomes "Money".
This is the reason why your program is unable to find any match. ("Money" is not the same as "Money Just Enough")
One way to solve this is to change your code so that you can receive an entire line as a string input.

Related

Trying to incorporate void functions into switch statements

I'm a novice coding student and trying to create a menu using structs, functions, and switch statements to make a mini database for a class assignment. I'm trying to implant the functions into the switch statements.
I'm getting errors on lines 87 and 137 and I'm not sure where I'm going wrong. Any help, explanation, or correction is much appreciated.
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
using namespace std;
// Jaret Clark
// Week 3 Interactive Assignment
// INT 499
// Prof. Joseph Issa
// 03/31/2022
struct EZTechMovie {
string name;
string *cast[10];
string rating;
};
void displaymovie(EZTechMovie movie, int cast_num) {
int i;
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
cout << "Your entry:\n";
//Movies
cout << endl;
cout << "Movie TITLE: " << movie.name;
cout << endl;
//Movie rating
cout << "Movie Rating: " << movie.rating;
cout << endl;
//Cast name
cout << "Main Cast Members: \n";
//loop for cast members ~ stores in array
for (int i = 0; i < cast_num; ++i) {
cout << movie.cast[i];
cout << endl;
}
}
void mainmenu() {
string movie_input;
int m;
cout << endl;
cout << "Would you like to store movies into database? (yes or no) ";
getline(cin, movie_input);
cout << endl;
if (movie_input == "yes") {
string cont;
string cast_name;
int x, m, n, i, cast_num;
EZTechMovie moviedb[100];
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
for (n = 0; n < 100; n++) {
cout << "Movie Title: ";
getline(cin, moviedb[n].name);
cout << endl;
cout << "Movie rating: ";
getline(cin, moviedb[n].rating);
cout << endl;
cout << "How many cast do you want to enter? ";
cin >> cast_num;
cout << endl;
cin.ignore();
for (i = 0; i < cast_num; i++) {
cout << "Cast name: First and Last name: ";
getline(cin, moviedb[n].cast[i]);
cout << endl;
}
cout << endl;
displaymovie(moviedb[n], cast_num);
cout << endl;
cout << "Add more movies? (yes or no) ";
getline(cin, cont);
if (cont == "no") {
break;
}
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
}
}
else if (movie_input == "no") {
return;
}
else {
cout << "INVALID Input";
mainmenu();
}
}
// menu
void movieMenu() {
int choice;
EZTechMovie movie;
do {
cout << "***********************Welcome to EZTechMovie Movie Entry Menu***********************" << endl;
cout << "Press 1 to Enter Movie Info - Name, Cast Members, and Rating.\n";
cout << "Press 2 to Retrieve movie info recently entered.\n";
cout << "Press 3 To Quit program.\n";
// evaluate menu options in switch case
switch (choice) {
case 1:
mainmenu();
break;
case 2:
displaymovie(EZTechMovie movie, int cast_num);
break;
case 3:
cout << "Thank you and Goodbye!";
break;
default:
cout: "Invalid Selection. Try again!\n";
}
//get menu selection
cin >> choice;
} while (choice != 3);
}
int main() {
movieMenu();
}
Regarding the error on line 87 (getline(cin, moviedb[n].cast[i]);) :
moviedb[n].cast[i] is a std::string*, not std::string like you might have meant.
A quick compilation fix would be to use:
getline(cin, *(moviedb[n].cast[i]));
i.e. dereference the pointer.
However - this code raises other design/programming issues:
Why do you use std::string* and not std::string in the first place.
Why do you use C style array instead of std::vector (or std::array if you can commit to the size). This is relevant for both: string *cast[10]; and EZTechMovie moviedb[100];

Unable to solve the probelm

In the adding user section in the code below, I am unable to type any characters for the "Add another person?(y/n): " question. it just jumps back to entering age. How do I fix this?
I've tried to change ans into a string, implement a while loop to force the question to show up, and many other things. It just seems that nothing works and I've been trying it for the good part of two hours
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main()
{
char ans;
int people;
int option;
int count = 0;
struct data
{
string name;
int age;
char gender;
string comments;
}person[100];
// homescreen
homescreen:
cout << "Welcome to the Data Base!" << endl;
cout << endl;
// displaying all people
for (int list = 0; list < count; list++)
{
cout << list << ".) " << person[list].name << endl;
}
cout << endl;
cout << "[1] View Person" << endl;
cout << "[2] Add Person" << endl;
cout << "[3] Edit Person" << endl;
cout << "[4] Delete Person" << endl;
cout << "[5] Exit" << endl;
cout << "Choose Option: "; cin >> option;
// using options
while (option != 5)
{
if (option == 1)
{
view:
for (int list2 = 0; list2 < count; list2++)
{
cout << list2 << ".) " << person[list2].name << endl;
}
cout << endl;
cout << "Enter number of person you want: "; cin >> people;
system("cls");
cout << "Name: " << person[count].name << endl;
cout << "Age: " << person[count].age << endl;
cout << "Gender: " << person[count].gender << endl;
cout << "Comments: " << person[count].comments << endl << endl;
cout << "View another person?(y/n): "; cin >> ans;
if (ans == 'y')
{
system("cls"); goto view;
}
else if (ans == 'n')
{
system("cls"); goto homescreen;
}
}
if (option == 2)
{
add:
system("cls");
cout << "Name: "; cin >> person[count].name;
system("cls");
cout << "Age: "; cin >> person[count].age;
system("cls");
cout << "Gender(M/F/H): "; cin >> person[count].gender;
system("cls");
cout << "Comments: "; cin >> person[count].comments;
count++;
system("cls");
cout << "Add another person?(y/n): "; cin >> ans;
if (ans == 'y')
{
system("cls");
goto add;
}
else if (ans == 'n')
{
system("cls");
goto homescreen;
}
}
}
}
If you anybody can help me I'd be grateful
The goto statements in your code makes the program really good
spaghetti
structure and that is not
good.
Therefore, think instead of goto other options, such as infinite
while loop which will break once the user enters the n or moving
the code to the function.
Secondly what if you have not entered any persons and choosing the
option 1. You still output the attributes of the person as
count is initialized zero at least. Remember the attributes are
not initialized at this point. Accessing the uninitialized
variables will invoke undefined
behavior. Therefore,
provide a check (something like if(count > 0) )before you execute the code in option 1.
In addition to that, remember that
std::endl flushes the output buffer, and '\n' doesn't. Therefore, most of
the cases you might wanna use just
\n.
Last but not the least, use std::vector instead of the using C style arrays with some predefined size. What if the user has more than 100 inputs? The solution in C++ is std::vector, which can expand dynamically as its storage is handled automatically.
Following is a possible solution to your program, in which the comments will guide you through to the things that I mentioned above.
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
struct Data
{
std::string name;
int age;
char gender;
std::string comments;
Data(const std::string& n, int a, char g, const std::string& c) // provide a Constructor
:name(n), age(a), gender(g), comments(c)
{}
};
void debugMsg(const std::string& msg)
{
system("cls");
std::cout << "\n\n\t\t" << msg << "\n\n";
Sleep(3000);
}
int main()
{
std::vector<Data> person; // use std::vector to store the datas
while (true) // loop: 1
{
system("cls");
std::cout << "Welcome to the Data Base! \n\n";
std::cout << "[1] View Person\n";
std::cout << "[2] Add Person\n";
std::cout << "[3] Edit Person\n";
std::cout << "[4] Delete Person\n";
std::cout << "[5] Exit\n";
std::cout << "Choose Option: ";
int option; std::cin >> option;
switch (option) // use switch to validate the options
{
case 1:
{
while (true) // loop - 2 -> case 1
{
// if no data available to show -> just break the loop 2 and return to the outer loop(i.e, loop 1)
if (person.empty()) { debugMsg("No person available to show ....going to main manu...."); break; }
// otherwise: displaying all people
for (std::size_t index = 0; index < person.size(); ++index)
std::cout << index << ".) " << person[index].name << "\n";
std::cout << "\nEnter number of person you want: ";
std::size_t index; std::cin >> index;
// if the index is not valid -> just break the loop 2 and return to the outer loop(i.e, loop 1)
if (index < 0 || index >= person.size()) { debugMsg("Sorry, wrong index!... returning to the main menu......"); break; }
system("cls");
std::cout << "Name: " << person[index].name << std::endl;
std::cout << "Age: " << person[index].age << std::endl;
std::cout << "Gender: " << person[index].gender << std::endl;
std::cout << "Comments: " << person[index].comments << std::endl << std::endl;
std::cout << "View another person?(y/n): ";
char ans; std::cin >> ans;
if (ans == 'y') { system("cls"); continue; } // just continue looping
else if (ans == 'n') { break; } // this will break the loop 2 and return to the outer loop(i.e, loop 1)
else { debugMsg("Sorry, wrong option!... returning to the main menu......"); break; }
}
} break;
case 2:
{
while (true) // loop - 3 -> case 2
{
system("cls");
std::string name, comments; int age; char gender;
std::cout << "Name: "; std::cin >> name;
std::cout << "Age: "; std::cin >> age;
std::cout << "Gender(M/F/H): "; std::cin >> gender;
std::cout << "Comments: "; std::cin >> comments;
// simply construct the Data in person vector in place
person.emplace_back(name, age, gender, comments);
std::cout << "\n\nAdd another person?(y/n): ";
char ans; std::cin >> ans;
if (ans == 'y') { system("cls"); continue; }
else if (ans == 'n') { system("cls"); break; } // same as case 1
else { debugMsg("Sorry, wrong option!... returning to the main menu......"); break; }
}
} break;
case 3: { /*code*/ debugMsg("Sorry, Not implemented!... returning to the main menu......"); } break;
case 4: { /*code*/ debugMsg("Sorry, Not implemented!... returning to the main menu......"); } break;
case 5: return 0; // if its 5, just retun the main
default: break;
}
}
return 0;
}
As mentioned above, using "goto" is a bad style, so i would suggest structure your program a little. Below is my version.
Naturally, I did not add any checks and controls, the author will be able to do this on his own. But main logics should work. And, of course, it is better to use vector instead of static array.
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
enum options { OPT_VIEW = 1, OPT_ADD = 2, OPT_EDIT = 3, OPT_DELETE = 4, OPT_EXIT = 5 };
struct data
{
string name;
int age;
char gender;
string comments;
};
class App
{
private:
data person[100];
int count = 0;
public:
App();
void Run();
int HomeScreen();
void View();
void Add();
};
App::App() : count(0)
{}
void App::Run()
{
int option = HomeScreen();
while(option != OPT_EXIT)
{
switch(option)
{
case OPT_VIEW:
View();
break;
case OPT_ADD:
Add();
break;
}
option = HomeScreen();
}
}
int App::HomeScreen()
{
int option = 0;
cout << "Welcome to the Data Base!" << endl;
cout << endl;
// displaying all people
for(int list = 0; list < count; list++)
{
cout << list << ".) " << person[list].name << endl;
}
cout << endl;
cout << "[1] View Person" << endl;
cout << "[2] Add Person" << endl;
cout << "[3] Edit Person" << endl;
cout << "[4] Delete Person" << endl;
cout << "[5] Exit" << endl;
cout << "Choose Option: "; cin >> option;
return option;
}
void App::View()
{
char ans = 0;
do
{
int people = 0;
for(int list2 = 0; list2 < count; list2++)
{
cout << list2 << ".) " << person[list2].name << endl;
}
cout << endl;
cout << "Enter number of person you want: "; cin >> people;
system("cls");
cout << "Name: " << person[people].name << endl;
cout << "Age: " << person[people].age << endl;
cout << "Gender: " << person[people].gender << endl;
cout << "Comments: " << person[people].comments << endl << endl;
cout << "View another person?(y/n): "; cin >> ans;
}
while(ans == 'y');
system("cls");
}
void App::Add()
{
char ans = 0;
do
{
system("cls");
cout << "Name: "; cin >> person[count].name;
system("cls");
cout << "Age: "; cin >> person[count].age;
system("cls");
cout << "Gender(M/F/H): "; cin >> person[count].gender;
system("cls");
cout << "Comments: "; cin >> person[count].comments;
count++;
system("cls");
cout << "Add another person?(y/n): "; cin >> ans;
}
while(ans == 'y');
system("cls");
}
int main()
{
App program;
program.Run();
}

C++ How do i display the input like a receipt after the user has typed them

Hi im creating a cinema ticket operator as a self short project but i am a bit stuck on how to make the results of what the user inputs show up at the end summed up like on a receipt. Thanks in advance.
This is my code :
#include <iostream>
#include <string>
using namespace std;
int selectStaff();
int selectDate();
int selectMovie();
int printReceipt(int a);
string name, date;
int main()
{
int movie;
selectStaff();
date = selectDate();
movie = selectMovie();
printReceipt(movie);
return 0;
}
int printReceipt(int a)
{
if (a == 1) {
cout << "Deadpool" << endl;
}
else {
cout << "Goosebumps" << endl;
}
return 0;
}
int selectStaff() {
cout << "Welcome to FILM Screen Cinema" << endl;
cout << endl;
cout << "ENTER STAFF/OPERATOR'S NAME: " << endl;
cin >> name;
return 0;
}
int selectDate() {
cout << endl;
cout << "ENTER DATE:";
cin >> date;
return 0;
}
int selectMovie() {
int movie;
cout << endl;
cout << "CHOOSE A MOVIE THAT IS SCREENING TODAY:" << endl;
cout << endl;
cout << "Press 1 for first option & 2 for second option" << endl;
cout << endl;
cout << "[1] Deadpool" << endl << "[2] Goosebumps" << endl;
cin >> movie;
return 0;
}
I want all the required input to be displayed at the bottom so when it prints, the user can view the summary. I also need a closing message that says "thank you"
You have all of the variables lined up to do this neatly and simply. Just edit your print receipt function to look something like:
Int printreceipt(int a) {
string title;
if (a==1) {
title = "Deadpool";
} else {
title == "Goosebumps";
}
cout << "Cashier: "; cout << name << endl << endl; //say the operator's name and add a line
cout << "Date: " << date << endl; //say the date
cout << "Movie: " << title; //say the title of the movie
cout << endl << endl; //add a line
cout << "Thank you for choosing this cinema! Enjoy!"; //Thank you message :D
}
To give you results similar to:
Cashier: Guy
Date: May 5, 2017
Movie: Deadpool
Thank you for choosing this cinema! Enjoy!

Difficulties with saving a text file using ofstream

Right now my problem seems to be focused on the saveFile function.
I will post the entire program here, so dont be ired when see a whole bunch of code... just look at the saveFile function at the bottom... I am posting all the code JUST IN CASE it will help you help me solve my problem.
Now for defining the apparent problem to you all: I can edit the file throughout the life of the console app with the updateSale function as I run it, but when I use the saveFile function and put in 'y' to save, the differences that are visible after using the updateSales function DO NOT get saved to the actual sales file called "salespeople.txt" and I do not understand why.
this is what the salespeople.txt looks like:
Schrute 25000
Halpert 20000
Vance 19000
Hudson 17995.5
Bernard 14501.5
now here is the program:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//variables--------------------------------------------------------
int lineCount = 0;
//prototypes-------------------------------------------------------
int getIndexLargest(string[], double[]);
void displaySalesPeople(string[], double[]);
bool readSalesFile(string[], double[]);
void updateSales(string[], double[]);
int saveFile(string, string[], double[], int);
int main()
{
string fileName;
int arrayLength;
ifstream readSales;
string salesPersonName[5];
double saleAmount[5];
bool flag = false;
int options;
do
{
cout << "1) Open sales person file. "<< endl;
cout << "2) Display sales person information. "<< endl;
cout << "3) Update sales. " << endl;
cout << "4) Get best sales person. " << endl;
cout << "5) Exit. " << endl;
cout << "Please enter a number 1-5 to select an option." <<endl;
cin >> options;
if(options == 1)
{
flag = readSalesFile(salesPersonName, saleAmount);
}
else if(options == 2)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
displaySalesPeople(salesPersonName, saleAmount);
}
else if(options == 3)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
updateSales(salesPersonName, saleAmount);
}
else if(options == 4)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
getIndexLargest(salesPersonName, saleAmount);
}
else if(options == 5)
{
char choice;
cout << "Enter character y to save... anything else will exit without saving: " << endl;
cin >> choice;
if(choice == 'y')
{
saveFile(fileName, salesPersonName, saleAmount, arrayLength);
cout << "File saved. " << endl;
}
else
{
cout << "closing program" << endl;
}
}
}
while(options != 5);
return 0;
}
//functions---------------------------------
bool readSalesFile(string salesPersonName[], double saleAmount[])
{
bool flag = false;
ifstream readSales;
string fileName;
cout << "Please enter the path to your sales people file: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
while(readSales.fail())
{
cout << "Failed. Please enter the path to your sales file again: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
}
if(readSales.good())
{
flag = true;
cout << lineCount;
string name = " ";
double amount =0.00;
int i = 0;
while(!readSales.eof())
{
readSales >> name;
readSales >> amount;
salesPersonName[i] = name;
saleAmount[i] = amount;
i++;
}
for(i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
readSales.close();
}
readSales.close();
return flag;
}
void displaySalesPeople(string salesPersonName[], double saleAmount[])
{
for(int i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
}
void updateSales(string salesPersonName[], double saleAmount[])
{
bool flag = false;
string findName;
double moneyAmount;
cout << "Enter name of sales person you want to modify: " << endl;
cin >> findName;
for(int i = 0; i < 5; i++)
{
if(findName == salesPersonName[i])
{
cout << "Enter the sale amount you would like to modify: " << endl;
cin >> moneyAmount;
saleAmount[i] += moneyAmount;
cout << saleAmount[i] << endl;
flag = true;
}
}
if(flag == false)
{
cout << " name not found" << endl;
}
}
int getIndexLargest(string salesPersonName[], double saleAmount[])
{
ifstream readSales;
while(!readSales.eof())
{
double largestSale = 0.00;
string largestSalesPerson;
int i = 0;
lineCount++;
readSales >> salesPersonName[i];
readSales >> saleAmount[i];
if(saleAmount[i] > largestSale)
{
largestSale = saleAmount[i];
largestSalesPerson = salesPersonName[i];
}
cout << "Best sales person : "<< largestSalesPerson << " $" <<setprecision(2)<<fixed<< largestSale << endl;
}
}
int saveFile(string fileName, string salesPersonName[], double saleAmount[], int arrayLength)
{
ofstream saveFile(fileName.c_str());
saveFile.open(fileName.c_str());
for(int i = 0; i < 5; i++)
{
saveFile << salesPersonName[i] << " " << saleAmount[i] << endl;
}
saveFile.close();
return 0;
}
You are trying t open your file twice:
ofstream saveFile(fileName.c_str()); // this opens the file
saveFile.open(fileName.c_str()); // so does this
That will put the file in an error state so no writing will happen.
Just do this:
ofstream saveFile(fileName.c_str()); // this opens the file
And that should work.
Or else you can do this:
ofstream saveFile; // this does not open the file
saveFile.open(fileName.c_str()); // but this does
And that should work too.

The search function does not work

Here is my code. It's homework but i have done it all. But the search function does not work. I know Im doing something wrong in it. The user has to enter a name to search and it should display the whole entry. There is an error at the void search function which says "error C2120: 'void' illegal with all types"
// Awholenew world.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<process.h>
#include<iomanip>
#include<stdio.h>
#include<string.h>
#include<fstream>
#include<sstream>
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
struct main
{
char FName[20];
char Last[20];
char Address[30];
long Phone;
int ID;
long CNIC;
}obj;
class Main
{
public:
virtual void init()
{
cin.getline(obj.FName,20);
cout << "Enter Name: ";
cin.getline(obj.Last,20);
cout << "Enter Address: ";
cin.getline(obj.Address, 30);
cout << "Enter Phone: ";
cin>>obj.Phone;
}
void view()
{
cout << "Name: " << obj.Last<< endl;
cout << "Address: " << obj.Address << endl;
cout << "Phone: " << obj.Phone << endl;
cout << "CNIC: " << obj.CNIC << endl;
cout << "ID: " << obj.ID << endl;
}
virtual void search()
{
char choice4;
char Target[20];
int Found=0;
fstream fin;
if (fin.open("Main.txt", ios::in| ios::out) == NULL)
cout<<"File is empty" << endl;
else
cout<<"Enter Name: " << endl;
cin.getline(Target, 20);
while(!fin.eof() && Found ==0)
{
fin<< endl << obj.Last << endl <<obj.Address <<endl <<obj.Phone << endl << obj.CNIC << endl << obj.ID;
if (strcmp(Target, obj.Last) == 0)
Found =1;
}
if(Found)
{
Main::view();
}
else if (!Found)
printf("**There is no such Entry**\n");
fin.close();
}
void display()
{
char BUFFER[100];
ifstream fin("Main.txt");
while (!fin.eof())
{
fin.getline(BUFFER, 100);
cout << BUFFER << endl;
}
}
};
class Teacher : public Main
{
public:
void tinit()
{
ofstream fin("Main.txt", ios::app);
Main::init();
cout << "Enter CNIC of Teacher" << endl;
cin>>obj.CNIC;
fin<< endl << obj.Last << endl << obj.Address << endl << obj.Phone << endl << "Teacher CNIC: " << obj.CNIC << endl;
}
};
class Student : public Main
{
public:
void sinit()
{
ofstream fin("Main.txt", ios::app);
Main::init();
cout << "Enter ID of Student" << endl;
cin>>obj.Phone;
fin<< endl << obj.Last <<endl << obj.Address << endl << obj.Phone << endl << "Student ID" << obj.ID << endl;
}
};
class Employee : public Main
{
public:
void einit()
{
ofstream fin("Main.txt", ios::app);
Main::init();
cout << "Enter Employee CNIC" << endl;
cin>>obj.CNIC;
fin << endl << obj.Last <<endl << obj.Address << endl << obj.Phone << endl << "Employee CNIC: " << obj.CNIC << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Main* myarr[100];
Teacher* tearr[100];
Student* starr[100];
Employee* emarr[100];
int var=0;
int choice;
char input;
start:
printf("===============MAIN MENU===============");
printf("\n[1]Insert\n[2]Display All\n[3]Search\n[4]Exit\n");
printf("=======================================");
printf("\n\nEnter Your Choice: ");
cin >> choice;
switch(choice)
{
case 1:
label:
cout<< "Enter Choice s/t/e" << endl;
cin >> input;
if (input == 't')
tearr[var]->tinit();
if (input == 's')
starr[var]->sinit();
if (input == 'e')
emarr[var]->einit();
cout << " Enter another (y/n)? ";
cin >> input;
if (input == 'y')
goto label;
else
goto start;
break;
case 2:
myarr[var]->display();
break;
case 3:
myarr[var]->search();
break;
case 4:
cout << "Are you sure? y/n" << endl;
char in;
cin>>in;
if (in=='y')
getch();
else goto start;
break;
default:
return 0;
break;
return 0;
}
}
One problem I can see is:
fstream fin;
if (fin.open("Main.txt", ios::in| ios::out) == NULL)
The function fstream::open is declared as:
void open ( const char * filename,
ios_base:openmode mode = ios_base::in | ios_base::out );
as you can see its return type is void, so you cannot use it in the if expression.
The most glaring thing I noticed is that it looks like the struct of type 'main' stored in the obj variable is outside of any particular class instance. This means that every single object of type Main, Employee, Student or Teacher is only writing to a single obj outside of its own scope. ALL Employees, Teachers, Students, 'Mains' will be sharing whatever FName, Last, Address values you wrote last.
What you probably want is for each instance of Main to have its own FName, Last, Address, etc...
class Main
{
struct main
{
char FName[20];
char Last[20];
char Address[30];
long Phone;
int ID;
long CNIC;
}obj;
public:
virtual void init()
{
... rest of code here
please reduce your post to the main problem. if you just list everything in a single "code" block. noone can understand what you do.
1: don't use "goto" !(!!!!!)
2: you sould realy use bool instead of int for flags
3: don't use main / Main for structs or class names. it's actually reserved for the mainmathod (on some systems) and it is confusing to have one class and one struct with the same name (ignoring the case)
4: you're accessing the function Main::view(); in your search method. but on which object ? normaly you should load the data to an object and accessing it via this->view();
5: the whole concept appear wired. why are you using a textfile and a polymorphic class hierarchy ? the textfile dumps the hierarchy. maybe you should reconsider your class concept.