【发布时间】:2015-04-01 20:23:55
【问题描述】:
我有一个程序允许用户输入新记录(放入结构然后写入文件)、打印所有记录或编辑特定记录。我已经包含了我的功能。这些记录是用于女童子军 cookie 信息的。它有名称、数量、价格和成本。它打开文件要求用户输入名称,然后当它找到该名称时,它会将所有数据读入一个临时结构变量(与将其写入文件的内容相同),用户可以在其中更改数量和在读取它的同一个地方重写它。除了更新的数量之外,一切都应该是相同的。它完成了所有这些,但由于某种原因,它之前的所有其他记录都变为空或 0。我的错误是什么导致我在文件中的所有其他记录发生了变化。我只想编辑这个特定的。 这只是功能。非常感谢您的帮助!
功能代码:
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())' 是错误的 - 我没有读过去(这样做之后,这段代码是垃圾)
-
此代码不会按原样编译。请发布有问题的minimal example
-
这不能编译?我现在按原样运行它?我的包含是#include
#include #include #include #include #include #include -
这段代码不能复制粘贴到空白文件中编译。缺少的东西:main()、cookie 的实现、正在使用的标准库函数的#includes。