欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【sscanf、结构体排序】2012年北理复试上机题

程序员文章站 2022-06-07 23:49:37
...
【sscanf、结构体排序】2012年北理复试上机题

【sscanf、结构体排序】2012年北理复试上机题'

http://www.cnblogs.com/lyq105/archive/2009/11/28/1612677.html


#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
using namespace std;
 
struct Stu
{
    int num;
    string name;
    string sex;
    int age;
};
 
bool cmp(Stu a,Stu b)
{
    return a.num<b.num;
}
 
int main()
{
    char op[105];
    int i,num,age,n=3;
    Stu stu[105];
    stu[0].num=10;stu[0].name="wes";stu[0].sex="f";stu[0].age=23;
    stu[1].num=20;stu[1].name="ert";stu[1].sex="f";stu[1].age=45;
    stu[2].num=30;stu[2].name="str";stu[2].sex="t";stu[2].age=89;
 
    while(1)
    {
        gets(op);
 
        if(op[0]=='0')
            break;
        else if(op[0]=='I')//插入
        {
            char name[105],sex[105];
            int num,age;
 
            sscanf(op,"I%d,%[^,],%[^,],%d",&num,name,sex,&age);//sscanf用法
            stu[n].num=num;
            stu[n].name=name;
            stu[n].sex=sex;
            stu[n].age=age;
            n++;
 
            sort(stu,stu+n,cmp);
 
            for(i=0; i<n-1; i++)
                cout<<"("<<stu[i].num<<","<<stu[i].name<<","<<stu[i].sex<<","<<stu[i].age<<"),";
            cout<<"("<<stu[n-1].num<<","<<stu[n-1].name<<","<<stu[n-1].sex<<","<<stu[n-1].age<<")"<<endl;
        }
        else if(op[0]=='D')//删除
        {
            int t;
            sscanf(op,"D%d",&t);
            for(i=0; i<n; i++)
            {
                if(stu[i].num==t)
                {
                    if(i==n-1)
                    {
                        n--;
                    }
                    else
                    {
                        stu[i].num=stu[n-1].num;
                        stu[i].name=stu[n-1].name;
                        stu[i].sex=stu[n-1].sex;
                        stu[i].age=stu[n-1].age;
                        n--;
                    }
                    break;
                }
            }
 
            sort(stu,stu+n,cmp);
 
            for(i=0; i<n-1; i++)
                cout<<"("<<stu[i].num<<","<<stu[i].name<<","<<stu[i].sex<<","<<stu[i].age<<"),";
            cout<<"("<<stu[n-1].num<<","<<stu[n-1].name<<","<<stu[n-1].sex<<","<<stu[n-1].age<<")"<<endl;
        }
    }
 
    return 0;
}