本文介绍了与std :: vector一起使用fread时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第一次执行是成功的,没有任何错误,但是当它创建 Data.bin
时,使用 fread
会出现一些错误.对不起,我不知道该怎么问,所以请看一下程序.我评论了错误的陈述.
First time execution is success without any error but when it creates Data.bin
I get some error when I use fread
.Sorry I don't know how to ask it so please look at the program.I commented the error making statement.
#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;
}
}
推荐答案
您不应使用 sizeof(string)
或sizeof包含字符串的结构,这毫无意义,它只会为您提供类字符串的编译时间(静态)大小.您应该改用 string.size()
返回字符串的动态大小.
you shouldn't use sizeof(string)
or sizeof a structure that contains a string, that's meaningless, it just gives you the compile time (static) size of the class string. you should instead use string.size()
which returns the dynamic size of the string.
这篇关于与std :: vector一起使用fread时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!