【问题标题】:Can't read binary file in C++无法在 C++ 中读取二进制文件
【发布时间】:2017-03-05 14:19:47
【问题描述】:

我的代码正在运行,但它无法读取我输入的二进制文件的输出。它给出了一个垃圾值。该程序旨在允许用户选择一个选项。

  1. 添加项目并将其写入二进制文件。

  2. 显示已读取的二进制文件的输出。

有什么帮助吗?

#include <iostream>
#include <fstream>
using namespace std;

struct info
{
    char name[50];
    int price, quantity;    
};

void AddItem(info item)
{
    cin.ignore();
    cout<<"Enter the following data about an item: \n";
    cout<<"Item name: ";
    cin.getline(item.name,50);
    cout<<"Price per item: RM";
    cin>>item.price;
    cout<<"Quantity: ";
    cin>>item.quantity;

}

void DisplayItems(info item)
{
    cout<<"Item name: "<<item.name<<endl;
    cout<<"Price per item: "<<item.price<<endl;
    cout<<"Quantity: "<<item.quantity<<endl;    
}

int main()
{
    info item;
    int option;
    char again;

    cout<<"1. Add new item in the product file\n";
    cout<<"2. Display all items\n";
    cout<<"3. Exit\n";
    cout<<"select option: ";
    cin>>option;

    if(option==1)
    {
        fstream file("report.dat", ios::out|ios::binary);
        do
        {
            AddItem(item);
            file.write(reinterpret_cast<char*>(&item), sizeof(item));
            cout<<"Do you want to enter another record? (Y/N): ";
            cin>>again;
        }
        while(again=='Y'||again=='y');  
    }

    if(option==2)
    {
        fstream file("report.dat", ios::in|ios::binary);
        if(!file)
        {
            cout<<"Error in opening the file!";
            return 0;
        }

       file.read(reinterpret_cast<char*>(&item),sizeof(item));
        while(!file.eof())
        {
            DisplayItems(item);
            file.read(reinterpret_cast<char*>(&item),sizeof(item));
        }
        file.close();

    }

    if(option==3)
    {
        cout<<"Exit";
        return 0;
    }

    return 0;
}

这是我的输出的样子:

【问题讨论】:

  • “我无法从文件中读取”到底是什么意思?是否显示Error in opening the file!
  • “它给出了一个垃圾值”是什么意思?这就是二进制文件中的内容看起来像...
  • @AnthonyD。你可以参考附上的图片。输出屏幕应该给我一个值是吗?

标签: c++ fstream binaryfiles


【解决方案1】:

改变你的

void AddItem(info item)

void AddItem(info& item)

以便用户在该函数中的输入反映在实际参数中。

我还要更改该函数的名称。

【讨论】:

    【解决方案2】:

    尝试将report.dat 替换为repost.txt 我还要重新检查reinterpret_cast&lt;char*&gt;(&amp;item), sizeof(item) 如果还没有,请打开您在程序中创建的报告文件。

    【讨论】:

    • 重命名文件不会对代码产生任何影响。该程序非常基本,以至于在处理它时没有考虑文件扩展名。
    猜你喜欢
    • 2019-05-16
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2011-09-03
    • 2016-01-15
    相关资源
    最近更新 更多