I've been trying to figure out how to deal with pointers & structs. I wrote the following code.
#include <iostream>
using namespace std;
struct Person
{
char name[20]; //Question 2
int id;
};
const int max_num_of_childs=10;
struct Family
{
Person dad;
Person mom;
int num_of_childs;
Person* child[max_num_of_childs];
};
void add_child (Family& f)
{
char answer;
do
{
if (f.num_of_childs==max_num_of_childs)
{
cout << "no more children" <<endl;
return;
}
cout << "more child? Y/N" <<endl;
cin >> answer;
if (answer == 'Y')
{
f.child[f.num_of_childs] = new Person;
cout << "enter name and id" << endl;
cin >> f.child[f.num_of_childs]->name;
cin >> f.child[f.num_of_childs]->id;
f.num_of_childs++;
}
}
while (answer=='Y');
return;
}
void add (Family& f)
{
cout << "insert dad name & id" << endl;
cin >> f.dad.name >> f.dad.id;
cout << "\ninsert mom name & id" << endl;
cin >> f.mom.name >> f.mom.id;
add_child (f);
}
void print_child (const Family f) //Question 1
{
for (int i=0; i<f.num_of_childs; i++)
cout << "#" << i+1 << "child name: " << f.child[f.num_of_childs]->name << "child id: " << f.child[f.num_of_childs]->id << endl;
}
void print (const Family f)
{
cout << "dad name: " << f.dad.name << "\tdad id: " << f.dad.id << endl;
cout << "mom name: " << f.mom.name << "\tmom id: " << f.mom.id << endl;
print_child (f);
}
int main()
{
Family f;
f.num_of_childs=0;
add(f);
print(f);
return 0;
}
Why is the output of print_child() gibberish?
dad name: AAAA dad id: 11
mom name: BBBB mom id: 22
1child name: ï Uï∞ u u u h░├evhchild id: 6846053
2child name: ï Uï∞ u u u h░├evhchild id: 6846053
How can I define an array of chars with unlimited length? (using string also requires a defined length).
Why is the output of print_child() gibberish?
In the print_child() method, code is reaching out of initialized range of f.child array. There is:
void print_child (const Family f) //Question 1
{
for (int i=0; i<f.num_of_childs; i++)
cout << "#" << i+1 << "child name: " << f.child[f.num_of_childs]->name << "child id: " << f.child[f.num_of_childs]->id << endl;
}
I believe there should be:
void print_child (const Family f) //Question 1
{
for (int i=0; i<f.num_of_childs; i++)
cout << "#" << i+1 << "child name: " << f.child[i]->name << "child id: " << f.child[i]->id << endl;
}
i is always smaller then f.num_of_childs, so code will not reach uninitialized memory.
Apart of this there is one more small thing.
Usually integer class members get initialized to 0, but this is not guarantied. I would recommend initialization, to ensure that initial value of num_of_childs is 0 when object of Family class is created:
struct Family
{
Person dad;
Person mom;
int num_of_childs = 0;
Person* child[max_num_of_childs];
};
Related
consider this is my code:
void SportShoe::AddSportShoe() {
SportShoe MySepatu[SIZE];
int numOfShoe = 0;
nodeSport *tempShoe1;
while (numOfShoe < SIZE){
cout << "Please enter the Shoe ID : (eg. 23210) " << endl;
cin >> SportShoe::MySepatu[numOfShoe].ShoeID;
cout << "Please enter the Shoe Brand: (eg. Adidas) " << endl;
cin.sync();
cin.getline(SportShoe::MySepatu[numOfShoe].BrandShoe,100);
cout << "Please enter the price of the Shoe : (eg. RM123.22) " << endl;
cin >> SportShoe::MySepatu[numOfShoe].PriceShoe;
cout << endl;
//passing the value from 'MySepatu' to 'tempShoe'
SportShoe::MySepatu[numOfShoe].ShoeID = (tempShoe1->ShoeIDList);
SportShoe::MySepatu[numOfShoe].BrandShoe[100] = (tempShoe1->BrandShoeList[100]);
SportShoe::MySepatu[numOfShoe].PriceShoe = (tempShoe1->PriceShoeList);
//i do some dummy to see what stored in tempShoe1
cout << "ID =>> " << tempShoe1->ShoeIDList << endl;
cout << "Brand =>> " << tempShoe1->BrandShoeList << endl;
cout << "Price =>> " << tempShoe1->PriceShoeList << endl;
}
while (numOfShoe >= SIZE-1){
cout << ">> List is already full !! <<";
system("PAUSE");
MenuSportShoe();
}
}
The code can be run as usual and doesn't show any error on the compiler. But, when it reach to the 'cout' area it'll print out something like an address of a pointer. Not the value.
Actually i think i use the wrong method to pass the value. I don't have idea on how to assign them.
//Here my class declaration
class SportShoe {
private:
struct nodeSport {
int ShoeIDList;
char BrandShoeList[100];
float PriceShoeList;
nodeSport *last;
};
nodeSport *first = NULL;
struct Shoe {
int ShoeID;
char BrandShoe[100];
float PriceShoe;
}MySepatu[SIZE];
public:
void AddSportShoe();
};
*i use array because i want to set a limit of the node. The linked list is useful for the other function like 'delete' , 'display', & etc.
Have any opinion to solve this and upgrade my code?
Don't use c strings, use std::string. Don't use arrays, use std::array or std::vector or a similar container. This will sure fix your problem.
class SportShoe {
private:
struct nodeSport {
int ShoeIDList;
std::string BrandShoeList;
float PriceShoeList;
nodeSport *last;
};
nodeSport *first = NULL;
struct Shoe {
int ShoeID;
std::string BrandShoe;
float PriceShoe;
};
std::array<Shoe, SIZE> MySepatu;
public:
void AddSportShoe();
};
void SportShoe::AddSportShoe() {
std::array<SportShoe, SIZE> MySepatu;
int numOfShoe = 0;
nodeSport *tempShoe1;
while (numOfShoe < SIZE){
cout << "Please enter the Shoe ID : (eg. 23210) " << endl;
cin >> SportShoe::MySepatu[numOfShoe].ShoeID;
cout << "Please enter the Shoe Brand: (eg. Adidas) " << endl;
cin.sync();
std::getline(cin, SportShoe::MySepatu[numOfShoe].BrandShoe);
cout << "Please enter the price of the Shoe : (eg. RM123.22) " << endl;
cin >> SportShoe::MySepatu[numOfShoe].PriceShoe;
cout << endl;
//passing the value from 'MySepatu' to 'tempShoe'
SportShoe::MySepatu[numOfShoe].ShoeID = tempShoe1->ShoeIDList;
SportShoe::MySepatu[numOfShoe].BrandShoe = tempShoe1->BrandShoeList;
SportShoe::MySepatu[numOfShoe].PriceShoe = tempShoe1->PriceShoeList;
//i do some dummy to see what stored in tempShoe1
cout << "ID =>> " << tempShoe1->ShoeIDList << endl;
cout << "Brand =>> " << tempShoe1->BrandShoeList << endl;
cout << "Price =>> " << tempShoe1->PriceShoeList << endl;
}
while (numOfShoe >= SIZE-1){
cout << ">> List is already full !! <<";
system("PAUSE");
MenuSportShoe();
}
}
So the purpose of the program is to Create an array of 3 people, allow the user to populate the data in a for loop, ensure that the results are capitalized, and output the results.
These new projects instructions were to
1. Rewrite capitalize() as a method within the structure.
2. Rewrite printPerson() as a method within the structure
The program itself works just fine, it's just not in the format that my professor wanted. He said the point of it is to not use any arguments but again, I don't know what he means. I just started programming a few months ago and even though I'm trying I don't have a strong knowledge of the terminology.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Person {
string firstName;
string middleName;
string lastName;
int age;
string gender;
void capitalize(Person &arg);
void printPerson(Person arg);
};
Pretty sure these are the methods right here, but I'm not sure if the (person &arg) and (person arg) are the arguments itself or if they are parameters. I thought it was the "arg" part but I can't find a way to get the program to run without them as I'm pretty sure I need the & of operator to modify the information.
int main(void) {
Person myPerson;
Person a[3];
const int size = 5;
for (int i = 0; i <= 2; i++) {
cout << "What is First Name #" << i + 1 << "? ";
getline(cin, a[i].firstName);
cout << "What is Middle Name #" << i + 1 << "? ";
getline(cin, a[i].middleName);
cout << "What is Last Name #" << i + 1 << "? ";
getline(cin, a[i].lastName);
cout << "Age #" << i + 1 << "? ";
cin >> a[i].age;
cin.ignore();
cout << "Male or Female #" << i + 1 << "? ";
getline(cin, a[i].gender);
cout << endl;
}
for (int i = 0; i <= 2; i++) {
myPerson.capitalize(a[i]);
cout << "PERSON #" << i + 1 << endl;
cout << "~~~~~~~~~~~~~~~" << endl;
myPerson.printPerson(a[i]);
}
system("pause");
return 0;
}
Along with that, I don't know how to manipulate the functions to work without the "parameters/arguments" (I'm not sure the difference at this point) or without the "arg"
void Person::capitalize(Person &arg) {
transform(arg.firstName.begin(), arg.firstName.end(), arg.firstName.begin(), ::toupper);
transform(arg.middleName.begin(), arg.middleName.end(), arg.middleName.begin(), ::toupper);
transform(arg.lastName.begin(), arg.lastName.end(), arg.lastName.begin(), ::toupper);
}
void Person::printPerson(Person arg) {
cout << "\nFirst Name: " << arg.firstName << endl;
cout << "\nMiddle Name: " << arg.middleName << endl;
cout << "\nLast Name: " << arg.lastName << endl;
cout << "\nAge: " << arg.age << endl;
cout << "\nGender: " << arg.gender << endl;
cout << "\n\n";
}
The capitalize and the printPerson are now members (usually called methods) of the struct Person. This means that they operate on the member variables of an Person instance. Like this, you can just access all the classes members in these methods. See the following code. I also completed it with a constructor and made it slightly more readable.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Person {
public:
Person();
void readFromUserInput();
void capitalize();
void print();
public:
string firstName;
string middleName;
string lastName;
int age;
string gender;
};
Person::Person() :
firstName(""),
middleName(""),
lastName(""),
age(0),
gender("")
{
}
void Person::readFromUserInput()
{
cout << "What is the First Name ? ";
getline(cin, firstName);
cout << "What is Middle Name ? ";
getline(cin, middleName);
cout << "What is Last Name ? ";
getline(cin, lastName);
cout << "Age ? ";
cin >> age;
cin.ignore();
cout << "Male or Female ? ";
getline(cin, gender);
}
void Person::capitalize()
{
transform(firstName.begin(), firstName.end(), firstName.begin(), ::toupper);
transform(middleName.begin(), middleName.end(), middleName.begin(), ::toupper);
transform(lastName.begin(), lastName.end(), lastName.begin(), ::toupper);
}
void Person::print()
{
cout << "\nFirst Name: " << firstName << endl;
cout << "\nMiddle Name: " << middleName << endl;
cout << "\nLast Name: " << lastName << endl;
cout << "\nAge: " << age << endl;
cout << "\nGender: " << gender << endl;
cout << "\n\n";
}
int main(void)
{
const int NUM_PERSONS = 3;
Person a[NUM_PERSONS];
for (int i = 0; i < NUM_PERSONS; i++)
{
cout << "### " << (i + 1) << ". User:" << endl;
a[i].readFromUserInput();
cout << endl;
}
for (int i = 0; i < NUM_PERSONS; i++)
{
a[i].capitalize();
cout << "PERSON #" << i + 1 << endl;
cout << "~~~~~~~~~~~~~~~" << endl;
a[i].print();
}
system("pause");
return 0;
}
I'm working on an assignment in my first semester of C++ and I just can't figure out working syntax for it. I need to pass a struct as a parameter to a class function using a pointer. This code I've copied is my best attempt, and it will compile but it crashes when it asks for the first name. When I try variations in the syntax, I get errors about incomplete struct, undefined variables (warrior was or invalid operators. What am I doing wrong?
#include <iostream>
using namespace std;
class StarWars
{
public:
int totalNumber;
struct data_clone
{
int ID, timeCounter;
string name;
};
data_clone *warrior;
void createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
}
void input(struct data_clone *pointer, int total)
{
for(int i = 1; i <= total; i++)
{
cout << "For warrior number " << i << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> pointer[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> pointer[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> pointer[i].timeCounter;
}
}
void lifeSpan(struct data_clone *pointer, int total)
{
for(int i = 1; i <= total; i++)
{
cout << "Warrior number " << pointer[i].name << ": " << endl;
while(pointer[i].timeCounter > 0)
{
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is alive." << endl;
pointer[i].timeCounter--;
}
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
};
int main(void)
{
StarWars clones;
clones.createClone();
clones.input(clones.warrior, clones.totalNumber);
clones.lifeSpan(clones.warrior, clones.totalNumber);
}
You don't initialise the memory warrior points to, so you're working with uninitiailised memory - always a bad thing. There's two things to keep in mind here:
When working with pointers, always initialise the memory behind them first. Prefer using RAII concepts like std::unique_ptr / std::shared_ptr
void DoStuff(Widget* w);
std::unique_ptr<Widget> pw = std::make_unique<Widget>();
DoStuff(w.get());
When working with normal variables, use the dereference / reference operators to take a pointer to the variable.
void DoStuff(Widget* w);
Widget widget;
DoStuff(&w);
struct data_clone
{
int ID, timeCounter;
string name;
};
class StarWars
{
private:
data_clone *warrior;
int totalNumber;
public:
StarWars()
{
}
~StarWars()
{
delete[] warrior; // clean up
}
void createClone();
void input();
void lifeSpan();
};
void StarWars::createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
// construct structure baased on input
warrior = new data_clone[totalNumber];
}
void StarWars::input()
{
for(int i = 0; i < totalNumber; i++)
{
cout << "For warrior number " << i+1 << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> warrior[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> warrior[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> warrior[i].timeCounter;
}
}
void StarWars::lifeSpan()
{
std::cout<<"**********Print data**********\n";
for(int i = 0; i < totalNumber; i++)
{
cout << "Warrior number " << warrior[i].name << ": " << endl;
while(warrior[i].timeCounter > 0)
{
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is alive." << endl;
warrior[i].timeCounter--;
}
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
StarWars clones;
clones.createClone();
clones.input();
clones.lifeSpan();
return 0;
}
You never created your clones, you only read how many there should be.
Allocate space for them:
void createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
warrior = new data_clone[totalNumber];
}
Your array indexes are also off - an array of size N is indexed from 0 to N - 1.
But the more common way of handling this is to pass the amount to the constructor and let the object handle its own members:
class StarWars
{
public:
StarWars(int clones)
: totalNumber(clones),
warrior(new data_clone[clones])
{
}
void input()
{
for(int i = 0; i < totalNumber; i++)
{
cout << "For warrior number " << i << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> warrior[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> warrior[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> warrior[i].timeCounter;
}
}
void lifeSpan()
{
for(int i = 0; i < totalNumber; i++)
{
cout << "Warrior number " << i << ": " << endl;
while(warrior[i].timeCounter > 0)
{
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is alive." << endl;
warrior[i].timeCounter--;
}
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
private:
int totalNumber;
struct data_clone
{
int ID, timeCounter;
string name;
};
data_clone *warrior;
};
int main()
{
int number = 0;
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> number;
StarWars clones(number);
clones.input();
clones.lifeSpan();
}
Note that you need to handle the destructor, the copy constructor, and the assignment operator properly as well (left as an exercise).
class StarWars
{
private:
struct data_clone
{
int ID, timeCounter;
string name;
};
public:
StarWars()
{
warrior = new data_clone[4];
}
~StarWars()
{
delete[] warrior;
}
int totalNumber;
data_clone *warrior;
void createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
}
void input(struct data_clone *pointer, int total)
{
for(int i = 0; i < total; i++)
{
cout << "For warrior number " << i << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> pointer[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> pointer[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> pointer[i].timeCounter;
}
}
void lifeSpan(struct data_clone *pointer, int total)
{
for(int i = 0; i < total; i++)
{
cout << "Warrior number " << pointer[i].name << ": " << endl;
while(pointer[i].timeCounter > 0)
{
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is alive." << endl;
pointer[i].timeCounter--;
}
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
};
Note: I just hardcoded it which is not the correct way, it force you to enter only 4 tyeps of dataclone
"warrior = new data_clone[4];"
you will at least get your result
I've searched through the already asked questions, but I haven't found what I'm looking for.
I'm working with structures, where I store a person's details (first name, last name, birth date and so on...). The goal is then to create an array of pointers to these structures and make a list containing a group of people's information. the main function is vary basic so far.
#include <iostream>
#include "methods.h"
using namespace std;
void printMenu() {
cout << "\n Welcome to the Person program!" << endl
<< " Choose what you would like to do: " << endl
<< " 1. Insert person" << endl
<< " 2. Show person" << endl
<< " 3. Exit" << endl;
}
int main() {
char choice;
person p;
do {
printMenu();
cout << "\n Your choice: ";
cin >> choice;
cin.ignore();
switch(choice) {
case '1': setPerson(p); break;
case '2': getPerson(p); break;
default: cout << "\n Exiting..." << endl;
}
} while(choice == '1' || choice == '2');
return 0;
}
here's the methods.cc file
// methods.cc
#include <iostream>
#include "methods.h"
using namespace std;
static char dummy; // catches the '\n' left in the stream after the usage of cin >>
void setFirstName(char s[]) {
cout << "\n First name: ";
cin.getline(s, 25);
}
void getFirstName(const char s[]) {
cout << "\n First name: " << s << endl;
}
void setLastName(char s[]) {
cout << "\n Last name: ";
cin.getline(s, 25);
}
void getLastName(const char s[]) {
cout << "\n Last name: " << s << endl;
}
void setAddress(address & a) {
cout << "\n Street: ";
cin.getline(a.street, 25);
cout << "\n Number: ";
cin.getline(a.number, 6);
cout << "\n Town: ";
cin.getline(a.town, 25);
cout << "\n Zip code: ";
cin.getline(a.zip, 25);
cout << "\n Province: ";
cin.getline(a.province, 25);
}
void getAddress(const address & a) {
cout << "\n Street: " << a.street << endl;
cout << "\n Number: " << a.number << endl;
cout << "\n Town: " << a.town << endl;
cout << "\n Zip code: " << a.zip << endl;
cout << "\n Province: " << a.province << endl;
}
void setBirthDate(birthdate & bd) {
cout << "\n Day: ";
cin >> bd.day;
cin.get(dummy);
cout << "\n Month: ";
cin >> bd.month;
cin.get(dummy);
cout << "\n Year: ";
cin >> bd.year;
cin.get(dummy);
}
void getBirthDate(const birthdate & bd) {
cout << "\n Day: " << bd.day << endl;
cout << "\n Month: " << bd.month << endl;
cout << "\n Year: " << bd.year << endl;
}
void setGender(char & g) {
cout << "\n Gender: ";
cin >> g;
cin.get(dummy);
}
void getGender(const char & g) {
cout << "\n Gender: " << g << endl;
}
void setPerson(person & p) {
setFirstName(p.firstName);
setLastName(p.lastName);
setAddress(p.location);
setBirthDate(p.bd);
setGender(p.gender);
}
void getPerson(const person & p) {
getFirstName(p.firstName);
getLastName(p.lastName);
getAddress(p.location);
getBirthDate(p.bd);
getGender(p.gender);
}
The program works fine, but, after entering all the information and prompting the program to display the entered data, the first three fields (first name, last name and street) all show the same output, that is, the street's name... somehow the first and last names are not saved into the respective char arrays...
for example, say I enter A and B as first and last name then C as the street name, the output will be
First name: C
Last name: C
Street: C
... then from here, the output is correct...
EDIT: btw, I haven't used the string type on purpose. Being it object-oriented, it is not covered in the programming course, so I'm stuck with the c string type (arrays of chars or pointers to char)
EDIT 2: here's the methods.h file. I've found the error myself. see comments in the code in struct person
// methods.h
#ifndef METHODS_H
#define METHODS_H
struct address {
char street[15];
char number[6];
char town[15];
char zip[6];
char province[3];
};
struct birthdate {
int day;
int month;
int year;
};
struct person {
char firstName[25]; // error due to me omitting the array length.
char lastName[25]; // same here, I had written char firstName[] & char lastName[]
address location;
birthdate bd;
char gender;
};
// base methods
void setFirstName(char s[]);
void getFirstName(const char s[]);
void setLastName(char s[]);
void getLastName(const char s[]);
void setAddress(address & a);
void getAddress(const address & a);
void setBirthDate(birthdate & bd);
void getBirthDate(const birthdate & bd);
void setGender(char & g);
void getGender(const char & g);
void setPerson(person & p);
void getPerson(const person & p);
#endif
thanks for all your advice!
I have an Addressbook C++ program that compiles and everything, but I cannot figure out how to write it to a file that saves the data each time it exits. Here is my code:
//AddressBook Program
#include <iostream>
#include <string.h>
#include <cstdlib>
#include <stdio.h>
using namespace std;
class AddressBook{
public :
AddressBook()
{
count = 0;
}
void AddEntry();
void DisplayAll();
void DisplayEntry(int i); // Displays one entry
void SearchEntry();
int MainMenu();
struct Entry_Struct
{
char firstName[ 15 ] ;
char lastName[ 15 ] ;
char birthday[ 15 ] ;
char phone[ 15 ] ;
char email[ 15 ] ;
};
Entry_Struct entries[100];
unsigned int count;
};
void AddressBook::AddEntry()
{
cout << "Entry number " << (count + 1) << " : " << endl;
cout << "Enter First Name: ";
cin >> entries[count].firstName;
cout << "Enter Last Name: ";
cin >> entries[count].lastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].phone;
cout << "Enter Email: ";
cin >> entries[count].email;
++count; // tally total entry count
}
void AddressBook::DisplayEntry(int i)
{
cout << "Entry[" << i + 1 << "] : " << endl; // states # of entry
cout << "First name : " << entries[i].firstName << endl;
cout << "Last name : " << entries[i].lastName << endl;
cout << "Date of birth : " << entries[i].birthday << endl;
cout << "Phone number : " << entries[i].phone << endl;
cout << "Email: " << entries[i].email << endl;
}
void AddressBook::DisplayAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DisplayEntry(i);
}
void AddressBook::SearchEntry()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].lastName) == 0)
{
cout << "Found ";
DisplayEntry(i);
cout << endl;
}
}
}
// Your class
AddressBook my_book;
int MainMenu()
{
int num;
bool bQuit = false;
// Put all your code into a while loop.
while(bQuit == false)
{
cout << "+-------------------------------------+" << endl;
cout << "| Address Book Menu |" << endl;
cout << "| |" << endl;
cout << "| 1- Add an entry |" << endl;
cout << "| 2- Search for an entry by last name |" << endl;
cout << "| 3- Display all entries |" << endl;
cout << "| 4- Exit |" << endl;
cout << "| |" << endl;
cout << "+-------------------------------------+" << endl;
cout << endl;
cout << "Please enter a number for one of the above options: ";
cin >> num;
cout << endl;
if (num == 1)
my_book.AddEntry();
else if (num == 2)
my_book.SearchEntry();
else if (num == 3)
my_book.DisplayAll();
else if (num == 4)
bQuit = true;
else
cout << "Invalid choice. Please try again" << endl;
cout << endl;
}
return 0;
}
int main (){
MainMenu();
return 0;
}
I've gone over my textbook all day and nothing I'm doing is working.
Here is a basic example of opening, and writing an output file,
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream outfile;
outfile.open ("addressbook.txt");
outfile << "Daffy,Duck,123 Main Street,Anytown,OH,USA,123-456-7890\n";
myfile.close();
return 0;
}
You need to have an inserter for your class. It's done using operator <<:
// Inside your class:
friend std::istream& operator<<(std::ostream& os, const AddressBook ab)
{
return os << /* ... */
}
As you can see, a user-defined operator << can be implemented in terms of the pre-defined standard inserter. You can use it in the following way:
std::ifstream in("yourtxtfile.txt");
in << my_book;