我正在使用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