我的任务是创建一个程序,该程序从用户那里获取名称和分数的输入,然后使用数组按降序对分数进行排序。我相信我已经弄清楚了一切,除了让我的程序在排序后实际显示分数。
我没有收到任何错误消息,但是当需要显示分数时,分数会无休止地生成,所有值均为零。它们应该在 x 个分数后停止生成。
非常感谢。
#include<iostream>
#include<string>
using namespace std;
void initializeArray(string*, int*, int);
void sortData(string*, int*, int);
void displayData(const string*, const int*, int);
int main()
{
int SIZE;
string *name;
name = new string[SIZE];
int *score;
score = new int[SIZE];
initializeArray(name, score, SIZE);
sortData(name, score, SIZE);
displayData(name, score, SIZE);
}
void initializeArray(string names[], int scores[], int size)
{
cout<<"how many scores will you enter? ";
cin>> size;
for(int count = 0; count<size; count++)
{
cout<<"name number "<<count+1<<": ";
cin>> names[size];
cout<<"score number "<<count+1<<": ";
cin>> *(scores + count);
}
}
void sortData(string names[], int scores[], int size)
{
int temp;
bool swap;
do
{
swap = false;
for(int count=0; count < (size-1); count++)
{
if(scores[count] > scores[count+1])
{
temp = scores[count];
scores[count] = scores[count+1];
scores[count+1] = temp;
swap = true;
}
}
}while(swap);//while there is a bool swap
}
void displayData(const string names[], const int scores[], int size)
{
for(int count = 0; count<size; count++)
{
cout<<"name "<<count<<": "<< scores[count]<<endl;
cout<<endl;
//cout<<"score "<<count+1<<": "<< *(scores + count)<<endl;
}
}
void initializeArray(string names[], int scores[], int size)
{
cout<<"how many scores will you enter? ";
cin>> size;
...
}
这里至少有一个问题。size
变量是initializeArray
的局部变量。用户输入的值永远无法在此函数之外看到。专门调用此函数不会更改 main 中 SIZE
的值。
如果您希望输入的大小在代码的其余部分中可见,则需要通过引用传递size
。
void initializeArray(string names[], int scores[], int& size)
{
cout<<"how many scores will you enter? ";
cin>> size;
...
}
这种额外的&
至关重要。