动态分配和显示

时间:2015-07-25 13:29:54

标签: c++

当我输入 Salim Oman 88.4 时,显示输出E.G时出现问题 该功能仅显示名称和国家的第一个字母,即 S O 88.4 ,我想显示整个名称

//这是Display()函数

void Display(char ** Names, char ** countries, float * Grades, int num_names)
{
int i;
 for (i=0;i<num_names;i++)
 {
    cout<<fixed<<showpoint<<setprecision(2);
    cout<<** Names<<"\t"<<** countries<<"\t"<<* Grades<<endl;
 }
}

我使用GetName()来读取用户输入的数据

void GetName(char name[], char country[], float & grade)
{
cout<<"Enter name: ";
cin>>name;
cout<<"Enter country: ";
cin>>country;
cout<<"Enter grade: ";
cin>>grade;
}

// AddName()函数分配新的指针数组并将先前数据复制到这些数组

void AddName(char **& Names, char **& Countries, float *& Grades, int & num_names)
{
char name[ MAXSIZE], country[ MAXSIZE];
float grade=0;
int i;
GetName(name,country,grade); // call 
//creat an array of character pointers
Names = new char * [num_names];
countries = new char * [num_names];
//creat an array of float
Grades = new float  [num_names];

for(i=0;i<num_names;i++)
{
    Names[i]= new char [strlen(name)+1]; //Allocate room for the enterd name
    strcpy(Names[i],name);//Copy the name to the nwely allocated space 
    countries[i] = new char [strlen(country)+1]; //Allocate room for the enterd name
    strcpy(countries[i],country);//Copy the country to the nwely allocated space 
    Grades[i]=grade;// Copy the grade to the Grades
}
++num_names; // increment the number of names to add another name 

}

1 个答案:

答案 0 :(得分:2)

cout<<** Names<<"\t"<<** countries<<"\t"<<* Grades<<endl;

应该是

cout<<Names[i]<<"\t"<<countries[i]<<"\t"<<Grades[i]<<endl;

NamescountriesGrades是数组。如果您想要访问数组的第n个元素,请执行此操作,例如array[n]而不是**array*array