厚街三屯到万江可园:一个C++编程的问题

来源:百度文库 编辑:神马品牌网 时间:2024/05/05 01:55:49
#include<iostream.h>
#include <string.h>

class stuInfor{
private:
int number;
char name[20];
char sex[1];
char major[20];
public:
stuInfor(int number,char name[20],char sex[1],char major[20]){number=0,name[20]='\0',sex[1]='\0',major[20]='\0';}
void print();
void set(char stuInfor_name[20],int a,char b[20],char c[1]);

};

void stuInfor::set(char stuInfor_name[20],int a,char b[20],char c[1])
{
number=a;
strcpy(name,stuInfor_name);
strcpy(major,b);
strcpy(sex,c);
}

void stuInfor::print()
{
cout<<"The student you want is"<<name<<","<<number<<"major is "<<major<<"sex is"<<sex<<endl;
}

void main()
{
char stuInfor_name[20];
int a;
char b[20];
char c[1];
stuInfor x('\0',0,'\0','\0');
cout<<"Please input the name."<<endl;
cin>>stuInfor_name;
cout<<"Input the number"<<endl;
cin>>a;
cout<<"Input the sex:m(male) or f(female)"<<endl;
cin>>c;
cout<<"Input the major"<<endl;
cin>>b;
x.set(stuInfor_name,a,b,c);
x.print();
}
我想编一个输入学生姓名,专业,学号和性别的程序。编译的时候没有错误,但是运行的时候运行不了。是不是字符串赋值的时候出了问题??我对字符串的赋值不是很清楚,查书也觉得没什么头绪。哪位高人能指点下小弟??谢谢!!~~:)

你的构造函数有问题,传入的只是一个地址值,不一定那个地址已经分配给程序了,所以你直接写入是有问题的.而且你的下标也有问题,数组的下标从0开始哦!这样的话你应该定义为21个字符
而且你这样写也不太好
建议改为:(在我的C++编译器下编译通过)
#include<iostream.h>
#include <string.h>

class stuInfor{
private:
int number;
char name[21]; //定义21个字符,保存20个字符,最后一个为结束符
char sex; //不用定义成数组了,只用一个字符不就可以了
char major[21];//定义21个字符,保存20个字符,最后一个为结束符
public:
stuInfor()//你是想写默认构造函数吧,不用给参数了
{
number=0;//最好每行一名,便于调试
name[0]='\0';
sex=-1;
major[0]='\0';
}
void print();
void set(char *stuInfor_name,int a,char *b,char c);

};

void stuInfor::set(char *stuInfor_name,int a,char *b,char c)
{
number=a;
strcpy(name,stuInfor_name);
strcpy(major,b);
sex=c;
}

void stuInfor::print()
{
cout<<"The student you want is"<<name<<","<<number<<"major is "<<major<<"sex is"<<sex<<endl;
}

void main()
{
char stuInfor_name[20];
int a;
char b[20];
char c;
stuInfor x;//调用默认构造函数就可以了
cout<<"Please input the name."<<endl;
cin>>stuInfor_name;
cout<<"Input the number"<<endl;
cin>>a;
cout<<"Input the sex:m(male) or f(female)"<<endl;
cin>>c;
cout<<"Input the major"<<endl;
cin>>b;
x.set(stuInfor_name,a,b,c);
x.print();
}

//这样可以
void main()
{
char stuInfor_name[20];
int a;
char b[20];
char c[1];

cout<<"Please input the name."<<endl;
cin>>stuInfor_name;
cout<<"Input the number"<<endl;
cin>>a;
cout<<"Input the sex:m(male) or f(female)"<<endl;
cin>>c;
cout<<"Input the major"<<endl;
cin>>b;
stuInfor x(a,stuInfor_name,b,c);
x.set(stuInfor_name,a,b,c);
x.print();
}

为什么要用char类型呢?用string很方便的,重载了很多算符比如用'+'表示连接。