请高手把一个C程序转成C++。

2024-12-02 03:26:07
推荐回答(3个)
回答1:

已经调整好了,并在VC++6.0上编译运行确认:

#include
#include
#define LEN sizeof(struct student)
struct student
{ char num[6];
char name[8];
char sex[2];
int age;
struct student *next;
} stu[10];

int main(void)
{ struct student *p,*pt,*head;
int i,length,iage,flag=1;
int find=0; /* 找到待删除元素 find=1,否则find=0 */
while (flag==1)
{
cout<<"input length of list(<10):";
cin>>length;
if (length<10)
flag=0;
}

/* 建立链表 */
for (i=0;i{p=(struct student *) malloc(LEN);
if (i==0)
head=pt=p;
else
pt->next=p;
pt=p;
cout<<"NO.:";
cin>>p->num;
cout<<"name:";
cin>>p->name;
cout<<"sex:";
cin>>p->sex;
cout<<"age:";
cin>>p->age;
}
p->next=NULL;
p=head;
cout<while(p!=NULL)
{
cout<<" "<num<<" "<name<<" "<sex<<" "<age<p=p->next;
}

/* 删除 */
cout<<"input age:"; /* 输入待删年龄 */
cin>>iage;
pt=head;
p=pt;
if (pt->age==iage) /* 链头是待删元素*/
{p=pt->next;
head=pt=p;
find=1;
}
else /* 链头不是待删元素*/
pt=pt->next;
while (pt!=NULL)
{if (pt->age==iage)
{p->next=pt->next;
find=1;
}
else /* 中间结点不是待删元素*/
p=pt;
pt=pt->next;
}
if (!find)
cout<<" not found "<
p=head;
cout<while (p!=NULL)
{
cout<<" "<num<<" "<name<cout<<" "<sex<<" "<age<p=p->next;
}
return 1;
}

回答2:

C和C++语法通用
不用多加修改就能在C++里编译成功

回答3:

#include
#include
using namespace std;

class CStudent
{
public:
char num[6];
char name[8];
char sex[2];
int age;

bool operator=(CStudent const &other)
{
return (this == &other);
}
};

int main()
{
list studs;
CStudent astu;
for (int i=0; i<10; ++i)
{
// 注意,未对非法输入做检查!
cout<<"No.="; cin>>astu.num;
cout<<"name="; cin>>astu.name;
cout<<"sex="; cin>>astu.sex;
cout<<"age="; cin>>astu.age;

studs.push_back(astu);
}
}