调用显示函数时,我的程序似乎遇到无限循环

时间:2018-01-24 09:19:06

标签: c++ data-files

以下摘录适用于创建“联系人”类的新对象。 create_contact函数用于通过成员函数getdata()获取新数据,从而创建新联系人并以排序方式将其附加到文件“contact_diary”。显示功能读取该文件以通过类成员函数'pudata()'在屏幕上显示列表。但是,在这些创建和显示功能中会考虑一些垃圾数据。请建议更正。

void create_contact(){
    contact p,q;    //objects
    cout<<"Enter data for new contact...";
    p.getdata();
    contact_diary_renew(); //this function opens and closes a file in out mode 
                           //to refresh it's contnts

    fin.open("contact_diary.txt",ios::binary|ios::in);
    fin.seekg(0);

    if(fin.eof()){             //when file is empty
        fout.open("contact_diary.txt",ios::binary|ios::out);
        fout.seekp(0);
        fout.write((char*)&p,sizeof(p));
        fout.close();
    }

    else{                       //when file is not empty
        int position=0,i;
        fin.seekg(0);

        while(!fin.eof()){  //to get location to enter new data

            fin.read((char*)&q,sizeof(q));

            if(strcmp(p.givename(),q.givename())<=0){
                break;
            }

            else{
                position+=1;
                fin.read((char*)&q,sizeof(q));
            }

        }

        fout.open("temp.txt",ios::binary|ios::out); //temporary file 

        fin.seekg(0);
        fout.seekp(0);

        for(i=0;i<position;i++){
            fin.read((char*)&q,sizeof(q));
            fout.write((char*)&q,sizeof(q));
        }

        fout.write((char*)&p,sizeof(p));

        while(!fin.eof()){
            fin.read((char*)&q,sizeof(q));
            fout.write((char*)&q,sizeof(q));
        }

        remove("contact_diary.txt");
        rename("temp.txt","contact_diary.txt");

        fout.close();
    }

    fin.close();
    cout<<"New contact created successfully!"<<endl;
    getch();
}

void display_contacts(){     //function to display the list
    contact p;  //object
    int count=0;

    fin.open("contact_diary.txt",ios::binary|ios::in);
    fin.seekg(0);

    while(!fin.eof()){
        fin.read((char*)&p,sizeof(p));
        p.showdata();
        count+=1;
    }

    if(count==0){
        cout<<"List empty!"<<endl;
    }

    else{
        cout<<"Total number of contacts: "<<count<<endl;
    }

    fin.close();
    getch();
}

0 个答案:

没有答案