【问题标题】:Error when using fread with std::vector将 fread 与 std::vector 一起使用时出错
【发布时间】:2012-10-17 12:48:43
【问题描述】:

第一次执行成功,没有任何错误,但是当它创建 Data.bin 时,我在使用 fread 时遇到了一些错误。 对不起,我不知道怎么问,所以请看程序。 我评论了错误声明。

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

typedef struct myStuff
{
    int cdno;
    string content,des;
}MS;

int main()
{
    vector<MS> data;
    int i=0;
    string in;
    FILE *fr=NULL,*fw=NULL;
    fr=fopen("Data.bin","rb");


    //----------------------------------------------------------------------
    if(fr!=NULL)
    {
        do
        {
            data.resize(++i);
        }while( fread(&data[i-1],sizeof(MS),1,fr) ); //ERROR
        fclose(fr);
    }
    else
        data.resize(++i);

    //----------------------------------------------------------------------
    while(1)
    {
        cout<<"Enter x to exit or c to continue updating data: ";
        cin>>in;
        if(in=="x"||in=="X")
        {
            fw=fopen("Data.bin","wb");
            fwrite(&data[i],sizeof(MS),i,fw);
            fclose(fw);
            exit(0);
        }
        else if(in=="c"||in=="C")
        {
            cout<<"Enter CD no: ";
            cin>>data[i-1].cdno;
            cout<<"Enter Contents: ";
            cin>>data[i-1].content;
            cout<<"Enter Description: ";
            cin>>data[i-1].des;
            data.resize(++i);
        }
        else
            cout<<"Try Again..."<<endl;
    }
}

【问题讨论】:

    标签: file vector error-handling fread


    【解决方案1】:

    你不应该使用 sizeof(string) 或 sizeof 包含字符串的结构,这是没有意义的,它只是给你类字符串的编译时间(静态)大小。你应该改用string.size(),它返回字符串的动态大小。

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2013-02-08
      • 2012-05-02
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多