I am a newbie and am trying write a phone book program. Entries in the phone book have to be one class and the phone book has to be a second class. A phone book will contain 100 entries.
I have two questions. First, I am getting an error indication at line 7 (name = name1) that I can't understand. Second, below I am pasting the code for creating the entry class, the phone book class, and also the function within the phone book class to read a text file in order to create 100 entries that will make up the phone book. Does this look right? I am sorry to ask such a general question. My instructor is very nice, but neither his lectures nor the book give me any confidence that this code will work.
The following are the explanation of the errors on line 7:
1. 'entry::name1' cannot appear in a constant-expression
2. cannot open output file Circle.exe: Permission denied
3. invalid in-class initialization of static data member of non-integral type 'std::string {aka std::basic_string<char>}'
4. ISO C++ forbids initialization of member 'name' [-fpermissive]
5. making 'name' static [-fpermissive]
The code is:
class entry {
private:
string name1, number1, note1;
public:
entry();
entry(string name, string number, string note){
name = name1;
number = number1;
note = note1;
}
void setName(string x){name1 = x;}
void setNumber(string y){number1 = y;}
void setNote(string z){note1 = z;}
string getName() {return name1;}
string getNumber() {return number1;}
string getNote() {return note1;}
};
class phoneBook {
int i, phoneBookCheck, num_entries;
public:
entry entryItem[100];
void readPhoneBook(){
phoneBookCheck = 0;
fstream fin;
fin.open("entries.txt");
if (fin.fail()){
cout << "Could not find an existing Phone book." << endl;
phoneBookCheck = 1;
return;}
for (i = 0; !fin.eof(); i++){
fin >> currentname;
entryItem[i].setName(currentname);
fin >> currentnumber;
entryItem[i].setNumber(currentnumber);
fin >> currentnote;
entryItem[i].setNote(currentnote);}
num_entries = i - 1;
}
~~~~~~~~~~~~~~~~~~~~~~~
(Note: currentname, currentnumber, and currentnote have been set up as global variables outside of the class blueprints.)
Please use code tags ([ code] [ /code] without the space).
Anyway, this doesn't make sense:
1 2 3 4 5
entry(string name, string number, string note){
name = name1;
number = number1;
note = note1;
}
Your goal is to set the membervariables based on input, thus the assignments have to be reversed (name1 = name, etc). Alternatively, use the initialization list: entry(string name, string number, string note) : name1(name), number1(number), note1(note) { }
(Protip: strings are heavy objects, so pass them by const reference!)
Your classes don't look wrong. I'd advise against calling the entire read-from-file stuff inside the constructor.
(Protip: You can use num_entries as the iterator/index in your reading function!)