【问题标题】:C++ fstream searching through a .txt for a structureC++ fstream 通过 .txt 搜索结构
【发布时间】: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。

标签: c++ struct fstream


【解决方案1】:
  • while(!data.eof()) 更改为while(data)
  • 为清楚起见,请在 while 循环的开头而不是结尾处读取文件中的记录。
  • 您可以在记录写入后跳出循环。
  • 在编写 cookies.txt 时,使用std::ios::binary | std::ios::in | std::ios::out 打开它。从std::ios::beg寻求。
  • 您已同时打开文件以进行读取和写入。这应该有效,但没有必要。在写入之前关闭文件以供读取。

【讨论】:

  • 谢谢!它在 ios::out 中默认创建一个新文件。我应该已经知道的事情。感谢您对新手的尊重和帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
相关资源
最近更新 更多