C - 将分类数据从文本转换为结构

时间:2014-11-03 16:24:51

标签: c struct fread

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

}

和我的主要()

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))光标向前移动(我想)

问题是输出与&#39; solitare.txt&#39; 。输出中有许多无法解释的字符,为什么字符会崩溃?

2 个答案:

答案 0 :(得分:0)

你可以做的一种方法是制作一系列列表:

std::list< std::list< card > > myListOfLists;

然后当您在文件中遇到******时,只需使用您的结构创建一个新列表,然后执行:

myListofLists.push_back(newList);

答案 1 :(得分:0)

您是用C或C ++编写的吗?这将产生很大的不同,因为文件i / o通常以非常不同的方式处理。 @Iaiello提供了一个依赖于C语言中没有的iostream的C ++答案。使用fread表明你可能想要一个C解决方案。所以,就是这样。

您可以使用fgetc从文件中提取单个字符,然后对其进行测试以查看它是否为星号并将其放回文件中以便稍后阅读。这个代码看起来像

int ch;
while( (ch = fgetc(fptr)) != EOF)
{

    if(ch == (int)'*')
    {
        //code to point to different list.  Perhaps switch statement and state variable
    }else
    {
        fread(&temp,sizeof(card),1,fptr);
        //code to apend temp to list
    }
}