我一直在搞一些代碼。我真的只是把事情整理在一起,探索如何從中得到我想要的東西。需要幫助刪除加載的數組並清除它從計數
現在一直困擾着我的是當我嘗試刪除一個用戶時,它將用戶留空而不是完全刪除它。我寧願它完全刪除/刪除該行,並在不刪除任何其他用戶數據的情況下調整計數。編號: 問題是我刪除了一個用戶後。當我列出每個用戶時,它顯示一個空白的用戶:傳遞:等等,而不是列出那些開始。如果我要保存文件,它將有5個空白空間。我寧願把它完全刪除,好像它們從來沒有在那裏開始。
這是我的加載代碼:
int Loadpdata()
{
ifstream fp_in;
if(count > 0)
{
cout << "pdata already Loaded.\nTotal of " << count << " users loaded." << endl;
return 0;
}
fp_in.open("p.data"); //Open user file
if(fp_in == NULL)
{
cout << "Could not open user file, exiting." << endl;
}
while(!fp_in.eof()) { //While there is something to read
getline(fp_in,userd[count]);
getline(fp_in,passd[count]); //Read a line from the file
getline(fp_in,aged[count]); //Read a line from the file
getline(fp_in,locationd[count]); //Read a line from the file
getline(fp_in,emaild[count]); //Read a line from the file
getline(fp_in,mid[count]); //Read a line from the file
cout << "User: " << userd[count] << " Loaded Successfully." << endl;
userstotal++;
count++;
}
fp_in.close(); //Done with the user file
cout << "Total Users Loaded: " << count << endl;
if(!count > 0)
{
cout << "Userlist is empty, exiting" << endl;
return -2;
}
return 0;
}
現在,這是我如何刪除用戶:
int Deletedata()
{
char user[80];
int logged_in=0;
while(!logged_in) { //Force user to login. Give a quit option if you'd like
cout << "Enter user name: ";
cin >> user;
int found = 0;
for(int x=0;x<count && !found;x++) { //For each user/password pair..
if(userd[x].compare(user) == 0) { //Matched the username
found = 1;
logged_in = 1;
userd[x].clear();
passd[x].clear();
aged[x].clear();
locationd[x].clear();
emaild[x].clear();
mid[x].clear();
}
}
if(!found) {
cout << "Invalid username!" << endl;
}
}
//Once we're done with that loop, they logged in successfully.
cout << "Deleted " << user << " Successfully." << endl;
return 0;
}
我越去想這個,我意識到我可能要報廢更多它並提出一種新的格式。
讀到你的數據那麼究竟是什麼問題?你沒有指定。有些東西不能正常工作?如果你想要一個代碼審查,請訪問http://codereview.stackexchange.com/ – OldProgrammer
如果你想更新數據文件,你需要寫出所有的記錄 - 當然省略了刪除的記錄。 – suspectus
你是否試圖從一個文件中序列化和反序列化一個類的實例?爲此使用一個庫,比如boost.serialization。如果您推出自己的產品,這種任務可能非常容易出錯。 – polkadotcadaver