我有一個允許用戶輸入新記錄(放入結構然後寫入文件),打印所有記錄或編輯特定記錄的程序。我已經包含了我的功能。這些記錄是針對girlcout cookie信息的。它有名稱,數量,價格和成本。它打開文件,要求用戶輸入名稱,然後當它找到名稱時,它將所有數據讀入臨時結構變量(與寫入文件的相同),用戶可以在其中更改數量和重寫它在它被讀取的同一個地方。除了更新的數量之外,所有內容都應該是相同的。它會執行所有這些操作,但由於某種原因會將所有其他記錄變爲null或0之前的所有其他記錄。我的錯誤是什麼讓這個改變了我文件中的所有其他記錄。我只想編輯這個特定的一個。 這只是功能。幫助真的很感激!C++ fstream通過.txt搜索結構
功能代碼:
void editField()
{
char input[20];
fstream data("cookies.txt", ios::in);
cookies test;
if (!data) {
cout << "Error opening file. Program aborting.\n";
return;
}
cout << "Please enter the name of the cookie you are searching for: ";
cin.getline(input,20);
data.read(reinterpret_cast<char *>(&test),
sizeof(test));
while (!data.eof())
{
if(strcmp(input,test.name) == 0) {
int position = data.tellp();
data.close();
data.clear();
data.open("cookies.txt", ios::binary | ios::out);
cout << "Please enter the new quantity for the cookie ";
cin >> test.quantity;
data.seekp(position-sizeof(test),ios::cur);
data.write(reinterpret_cast<char *>(&test), sizeof(test));
}
// Read the next record from the file.
data.read(reinterpret_cast<char *>(&test),
sizeof(test));
}
return;
}
像往常一樣'while(!data.eof())'是錯誤的 - 我沒有讀過去(在這樣做之後,這段代碼是垃圾) – 2015-04-01 20:32:44
這段代碼並不按原樣編譯。請發佈有問題的[最小示例](http://stackoverflow.com/help/mcve) – chwarr 2015-04-01 20:52:46
這不能編譯?我現在正在運行它?我是包含的#include 的#include 的#include 的#include 的#include 的#include 的#include –
Reaperr
2015-04-01 20:57:52