I've been recently trying to write a contacts list
but I keep facing some problems (sorry for poor english btw)
here's my code:
class contact{
private:
std::string name;
long int number;
public:
void append();
void search();
};
void contact::append(){
std::cin.ignore();
std::ofstream cnt;
cnt.open("contacts.dat", std::ofstream::app);
std::cout<<"Please enter the name\n";
std::getline(std::cin, name);
cnt << "Name: " << name << std::endl;
bool flag=true;
while(flag){
std::cout<< "Enter the number:\n";
std::cin >> number;
if(std::cin.good()){
try{
if(number == 0){
throw number;
}
else{
cnt << "number: +98" << number <<"\n\n";
flag=false;
break;
}
}
catch (...){
std::cout<<"Unvalid entry\n\a";
}
}
else{
std::cout<<"unvalid entry, please enter an integer\a"<<std::endl;
std::cin.clear();
std::cin.ignore(10000, '\n');
}
}
std::cout<<"Added Successfully";
cnt.close();
}
void contact::search(){
std::cin.ignore();
std::ifstream sr;
sr.open("contacts.dat");
std::string search_name;
bool found = false;
std::cout<<"Enter a name for finding its phone number\n";
std::getline(std::cin, search_name);
while(sr>>number){
sr>>name;
if(name == search_name){
std::cout<<"Name: "<<name<<std::endl;
std::cout<<"Number: "<<number<<std::endl;
found=true;
break;
}
}
if (found==false){
std::cout<<search_name<<" not found";
}
sr.close();
}
int main(){
contact cont;
int choice;
while (1) {
std::cout << "Enter Your Choice\n";
std::cout << "\t1. Add contact \n";
std::cout << "\t2. Find contacts \n";
std::cin >> choice;
switch(choice){
case 1:
cont.append();
break;
case 2:{
cont.search();
}
default:
std::cout<<"\ninvalid Choice\n\a";
}
}
}
I already added some contacts to contacts.dat via the program.
contacts.dat
:
Name: john
Number: +98911111111
Name: joe
Number: +98914523525
Name: example
Number: +98954645236
but when I try to run the code:
Enter Your Choice
1. Add contact
2. Display Contacts
2
Enter a name for finding its phone number
john
john not found
Aucun commentaire:
Enregistrer un commentaire