I'm trying to create a program that takes user input for a number of students then asks the user for students names and a test score. Names and test scores should be assigned to two arrays, we are not allowed to include <string>. The program then sorts the test scores, calculates the average, and displays all the data. My program compiles and runs but there is an error when trying to assign names for the students.
I think the problem has something to do with the getString() function???
Can someone please help me spot my error?
Code:
// Project 8: Test Scores
// October 31, 2008
// This program stores students and their respective test
// score in two seperate arrays, then calculates the
// average test score, and displays the students, their
// test score, and the average test score for the class.
#include <iostream>
#include <iomanip>
using namespace std;
//function Prototypes
int getSize();
char* getString(int i);
int stringLength(char string[]);
void stringCopy(char string[], char* ptr, int size);
void selSort(char** stu, int tes[],int size);
float avg(int tes[], int size);
int main()
{
int i, x, size = getSize();
char* stu[size];
int tes[size];
float average;
for(i = 0; i < size; i++)
{
cout << "Please enter student " << (i + 1) << "'s last name: ";
stu[i] = getString(i);
cout << "Enter that student's test score: ";
cin >> tes[i];
cout << endl;
}
selSort(stu, tes, size);
average = avg(tes, size);
cout << setw(12) << left << "Name"
<< setw(12) << left << "Score"
<< endl
<<"-------------------------\n";
for(i = 0; i < size; i++)
{
cout << setw(12) << left << stu[i]
<< setw(12) << left << tes[i]
<< endl;
}
cout << endl<< "The average test score is: " << average << endl;
cin >> x;
}
int getSize()
{
int size ;
cout << "How many test scores will you enter?: ";
cin >> size;
return size;
}
//----------------------------------------------------------------------------------------------------------
char* getString(int i)
{
int size = 80;
char string[size];
cin.getline(string, size);
cout << endl;
size = stringLength(string);
char* ptr = new char[size + 1];
stringCopy(string, ptr, size);
return ptr;
}
int stringLength(char string[])
{
int count = 0;
while(string[count] != '\0')
count++;
return count;
}
void stringCopy(char string[], char* ptr, int size)
{
for(int i = 0; i <= size; i++)
ptr[i] = string[i];
}
//---------------------------------------------------------------------------------------------------------
void selSort(char* stu[], int tes[],int size)
{
int temp, min;
char* stuTemp;
for( int i = 0; i < size; i++)
{
min = i;
for (int j = 1; j < size; j++)
{
if (tes[j] < tes[min])
min = j;
}
stuTemp = stu[i];
stu[i] = stu[min];
stu[min] = stuTemp;
temp = tes[i];
tes[i] = tes[min];
tes[min] = temp;
}
}
float avg(int tes[], int size)
{
int i;
float sum = 0, avg;
for(i = 0; i < size; i++)
{
sum += tes[i];
}
avg = (static_cast<float>(sum)/size);
return avg;
}