简体   繁体   中英

Error in file already exists

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!

1st run

Enter the name of account : Hassan

Account created

2nd run

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"

CODE

/*
********************
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 ...

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM