编译能过,但是输入数据就出错!
编译能过,但是输入数据就出错!
代码:
#include <string.h>
#include <iostream.h>
const int n=10;
struct Person
{
char* name;
int count;
}Leader[n];
void Election(Person Leader[],int n)
{
char* name;
cout < < "请输入候选人名: ";
cin> > name;
while(name!= "# ")
{
for(int i=0;i <n;i++)
if(strcmp(Leader[i].name,name)==0)Leader[i].count++;
cout < < "请输入: ";
cin> > name;
}
for(int i=0;i <n;i++)
cout < <Leader[i].name < < "得票数为, " < <Leader[i].count < <endl;
}
void main()
{
Election(Leader,n);
}
[解决办法]
为什么不把name定义成string?
[解决办法]
char* name;
===========
没有分配内存
[解决办法]
都C++ 了为啥不用string
[解决办法]
使用指针试一定要注意分配和释放内存
[解决办法]
很明显,没有分配内存
[解决办法]
#include <iostream>
#include <string>
using namespace std;
const int n=10;
struct Person
{
string name;
int count;
}Leader[n];
void Election(Person Leader[],int n)
{
string name;
cout < < "请输入候选人名: ";
cin> > name;
while(name!= "# ")
{
for(int i=0;i <n;i++)
if(Leader[i].name==name)Leader[i].count++;
cout < < "请输入: ";
cin> > name;
}
for(int i=0;i <n;i++)
cout < <Leader[i].name < < "得票数为, " < <Leader[i].count < <endl;
}
int main()
{
Election(Leader,n);
}
[解决办法]
using namespace std;
使用名字空间。。。提供了声明的作用域。。。可以增加库的重用性。。。
[解决办法]
char *name是指针
内存没分配
[解决办法]
对不起!当时随手写的没做调试,下面这个应该可以了:
#include <string.h>
#include <iostream.h>
const int n=3;
const int LEN=10;
struct Person{
char *name;
int count;
}Leader[n];
Person *Create(const char *name,int num)
{
Person *p = new Person;
int mn = strlen(name);
p-> name = new char[mn+1];
strcpy(p-> name,name);
p-> name[mn]= '\0 ';
p-> count = num;
return p;
}
void Free(Person *p)
{
if(p){
delete []p-> name;
// delete p;
}
}
Person *Copy(Person *o,Person *s)
{
if(o&&s){
int mn;
char *c = new char[mn=strlen(s-> name)+1];
if(c==0)return o;
strcpy(c,s-> name);
c[mn]= '\0 ';
delete []o-> name;
o-> name = c;}
return o;
}
bool Init(Person *p,int n)
{
if(!p)return false;
int count=0;
char *name = new char[LEN+1];
do{
cout < < "请输入候选人名,输入#号结束: ";
cin> > name;
name[LEN]=0;
if(strstr(name, "# "))break;
Person *t = Create(name,0);
Copy(&(p[count++]),t);
delete t;
}while(count <n);
delete []name;
return count> 0;
}
void Election(Person Leader[],int mn)
{
char* name = new char[LEN];
cout < < "请为候选人名投票,以#号结束: ";
cin> > name;
while(!strstr(name, "# ")/*name!= "# "*/){
for(int i=0;i <n;i++)
if(strcmp(Leader[i].name,name)==0)Leader[i].count++;
cout < < "请为候选人名投票,以#号结束: ";
cin> > name;}
delete []name; //--------------
for(int i=0;i <mn;i++)
cout < <Leader[i].name < < "得票数为, " < <Leader[i].count < <endl;
}
int main()
{
if(Init(Leader,n))
Election(Leader,n);
for(int i=0;i <n;i++)
Free(&Leader[i]);
return 0;
}