无法实现循环查找c++文件


//全部代码 
#include <iostream>
#include <fstream>
using namespace std;

//1-(1)定义staff结构体 
struct staff
{
    int num; 
    int age;
    char name[20];
    double pay;
};

int main()
{
    //1-(1)五名员工信息 
    staff staf[5] = {5200,23,"Ai",18000,5201,25,"Hua",25000,
                     5202,36,"Chun",14220,5203,45,"Qiu",65421,
                     5204,20,"Dong",22000};
    staff staf1;
    
    //1-(1)创建staff.dat磁盘文件
    //参数不能缺少ios::trunc
    //因为fstream:in|out模式下,文件不存在不会被创建
    //加上ios::trunc表示文件不存在则创建,存在则清空内容 
    fstream file("staff.dat",ios::in|ios::out|ios::binary|ios::trunc);
    if(!file)
    {
        cout<<"Open erroe!"<<endl;
        abort();
    }
    
    int i,num;
    cout<<"All staff: "<<endl;
    
    //1-(1)将员工信息存入文件 
    for(i=0; i<5; i++)
    {
        cout<<staf[i].num<<" "<<staf[i].age<<" "<<staf[i].name<<" "<<staf[i].pay<<endl;
        file.write((char*)&staf[i],sizeof(staf[i]));
    }
    
    //1-(2)在文件末尾加入一名员工信息 
    cout<<endl<<"Please add a new member: "<<endl;
    file.seekp(0,ios::end);
    cin>>staf1.num>>staf1.age>>staf1.name>>staf1.pay;
    file.write((char*)&staf1,sizeof(staf1));
    cout<<endl;

    //1-(3)输出文件所有员工数据 
    cout<<"All staff: "<<endl;
    file.seekg(0,ios::beg);
    for(i=0; i<6; i++)
    {
        file.read((char*)&staf[i],sizeof(staf[i]));
        cout<<staf[i].num<<" "<<staf[i].age<<" "<<staf[i].name<<" "<<staf[i].pay<<endl;
    }
    cout<<endl;
    
    //1-(4)查询员工 
    bool find;
    cout<<"Please enter the query number,enter 0 to end query: ";
    cin>>num;
    while(num)
    {
        find = false;
        file.seekg(0,ios::beg);
        for(i=0; i<6; i++)
        {
            file.read((char*)&staf[i],sizeof(staf[i]));
            if(num == staf[i].num)
            {
                cout<<staf[i].num<<" "<<staf[i].age<<" "<<staf[i].name<<" "<<staf[i].pay<<endl;
                find = true;
                break;
            }
        }
        if(!find)
            cout<<"No person found."<<endl;
        cout<<"Please enter the query number,enter 0 to end query: ";
        cin>>num; 
    }
    file.close();
    return 0;
}
为什么输入num值后程序就结束了








可以使用调试模式在 while(num)循环内部打断点观察是否进入循环,如果没有很可能是因为cin不跳过回车符号,下一次cin得到的还是一个回车符也就是空的输入,需要在每一次cin语句后面添加一句cin.get();跳过回车,