Reputation: 165
I am trying to create file for an account, after checking if file already exists or not! But I got stuck, because I am getting an unexpected run time error!
Enter the name of account : Hassan
Account created
Enter account name: Hassan
Account already exists
Enter the name of account : Hassan
Account created
This is the problem!!! and it creates file with the name "assan"
/*
********************
1. ADD ACCOUNT
********************
*/
void add_account(){
system("cls");
cout<<"\n\t******************************************\n";
cout<<"\t\tADD ACCOUNT MENU\n";
cout<<"\t******************************************\n";
//Taking account name
again:
Account new_account;
cout<<"\n\n\tPlease Enter the name of account : ";
cin.ignore(); //for clearing buffer
cin.getline(new_account.account_name,79);
if(create_file_for_account(new_account.account_name)==0)
goto again;
cout<<endl<<endl; system("pause");
return;
}
/*
********************
1(a). CREATE FILE OF ACCOUNT
********************
*/
int create_file_for_account(char file_name[])
{
//Check if file exists already
if(does_file_exist(file_name)){
cout<<"\n\nSorry, account already exists!";
return 0;
}
ofstream account;
account.open(file_name,ios::out);
//Check if file created successfully
if(account.good()){
cout<<"File created";
return true;
}
else{
return false;
}
}
/*
********************
1(b). CHECK IF FILE EXISTS
********************
*/
bool does_file_exist(char file_name[])
{
ifstream check(file_name, ios::ate);
if(check)
return true;
else{
return false;
}
}
Please help, I was trying for hours to catch error, but I can't As I am beginner in C++ :p Please ...
Upvotes: 0
Views: 627
Reputation: 1051
Actually the "cin.ignore" will discard only the first character of the input (if there is one) (see http://www.cplusplus.com/reference/istream/istream/ignore/)
So I'd assume that the "H" somehow got ignored...
Upvotes: 2