我正在使用C/C++开发项目。我从文件中读取时遇到问题。对于份额的代码C - 将文本中的分类数据转换为结构
//编辑我有一个结构,如:
struct card{
char color;
char suit;
char num[3];
char turned[5];
card *next;
};
struct cardlist{
card *top;
int counter;
cardlist *nextlist;
void create();
bool push(card *newcard);
void pop();
void showlist();
bool isempty();
};
我已经从 'solitare.txt' 阅读。并创建一个链接列表。 solitare.txt是这样的:
B C 3 Up
B C 6 Up
R D 4 Up
B C 2 Up
R H 3 Up
R D 8 Up
******
R H 6 Up
******
R H 8 Down
B S 9 Up
******
B S 2 Down
B C K Down
B S Q Up
我的功能:
void cardlist::create(){
top = NULL ;
counter = 0;
}
bool cardlist::isempty(){
if(top == NULL){
return true;
}
return false;
}
void cardlist::showlist(){
if(isempty()){
cout << "Liste bos." << endl ;
return;
}
card *temp = new card;
temp = top;
while(temp){
cout << temp->color << temp->suit << temp->num << temp->turned << endl;
temp = temp->next ;
}
}
bool cardlist::push(card *newcard){
card *temp = new card ;
temp = newcard;
temp->next = NULL ;
if(top == NULL){
top = temp ;
counter++;
return true;
}else{
temp->next = top ;
top = temp ;
counter++;
return true ;
}
return false;
}
void cardlist::pop(){
if(isempty()){
cout << "liste bos kart silinemez." << endl ;
return ;
}
card *removed = top ;
card *temp ;
temp = top;
top = top->next;
counter--;
delete removed;
}
和我的main()
FILE *fptr = fopen("solitaire.txt","r+");
if(fptr == NULL){
cout << "dosya acilamadi" << endl ;
}
cardlist l1;
l1.create();
int ch;
long pos = ftell(fptr);
while((ch = fgetc(fptr)) != EOF){
fseek(fptr,pos,SEEK_SET);
cout << "girildi" ;
card *temp = new card;
if(ch == (int)'*')
{
break ;
}else
{
fread(temp,sizeof(card),1,fptr);
l1.push(temp);
l1.showlist();
cout << endl ;
pos = ftell(fptr);
}
}
我FTELL用()取回光标,因为行(CH = fgetc(fptr))光标向前移动(我猜)
问题输出与'solitare.txt'不一样。输出中有许多莫名其妙的字符,为什么字符会崩溃?你可以做到这一点
那么你有什么问题呢?你是什么意思分组?也没有C/C++ – 4rlekin 2014-11-03 16:29:37
'fread(&temp,sizeof(card),1,fptr)'这是行不通的。最关心的是指针。 – 2014-11-03 16:30:47
含义fptr?如果是这样,也许你可以发布更多的代码?你也有编译错误?如果是这样请粘贴 – 4rlekin 2014-11-03 16:32:01