Hey guys for some reason my txt file gets messed up when they type in a unknown name in my lookup function i can't seem to see why this is happing
Code:
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
//Global Functions
//My own little system("pause") function :)
void wait();
///////////////////
void lookup();
void addname();
///////////////////
struct info
{
char name[100];
char address[100];
char telnumber[100];
};
int main()
{
cout<<"----------------Address Book----------------"<<endl;
cout<<"-------------------By: Me-------------------"<<endl;
cout<<"What do you want to do?"<<endl;
cout<<"[1]Look Up Name [2]Add Name [3]Leave"<<endl;
int mainchoice;
int mainloop = 0;
while(mainloop==0)
{
cin>>mainchoice;
switch(mainchoice)
{
case 1:
lookup();
mainloop=1;
break;
case 2:
addname();
mainloop=1;
break;
case 3:
return 0;
break;
default:
cin.clear();
cout<<"Try Agian";
wait();
}
}
return 0;
}
void lookup()
{
cout<<"Enter the name of the person you want to lookup"<<endl;
info lperson;
cin>>lperson.name;
char namelook[100];
fstream lookname("address.txt");//Something in here im not sure what though
while(!lookname.eof())
{
cin.clear();
lookname.getline(namelook,100,'\n');
if(!strcmpi(namelook,lperson.name))
{
lookname.getline(lperson.address,100,'\n');
lookname.getline(lperson.telnumber,100,'\n');
break;
}
}
if(strcmpi(namelook,lperson.name))
{
cout<<"Could Not Find Name Try Agian"<<endl;
lookname.close();
lookup();
exit(0);
}
lookname.close();
cout<<lperson.name<<endl;
cout<<lperson.address<<endl;
cout<<lperson.telnumber<<endl;
wait();
}
void addname()
{
cin.ignore(80,'\n');
cout<<"What is the name of the person you wish to add?"<<endl;
info aperson;
cin.getline(aperson.name,100,'\n');
cout<<"What is"<<aperson.name<<"Address?"<<endl;
cin.getline(aperson.address,100,'\n');
cout<<"And finnaly what is their telephone number(no need to enter a dash)"<<endl;
cin.getline(aperson.telnumber,100,'\n');
ofstream newname("address.txt",ios::app);
newname<<aperson.name<<endl;
newname<<aperson.address<<endl;
newname<<aperson.telnumber<<endl;
newname.close();
cout<<"Succesfully Added "<<aperson.name<<" to the address book"<<endl;
wait();
}
void wait()
{
cout<<"Press any key and enter to continue..."<<endl;
cin.ignore(80,'\n');
char wait[5];
cin>>wait;
}
If the person types a wrong name it adds stuff onto the first line in the file eg. if I enter lady(which doesn't exist in the file) it adds to my name brian which is at the top of the file like this
Code:
BriBrian
11520
5311145
and if I keep entering a invalid entry it just adds another Bri to my name
Thx In Advance Guys