나는 배열, 포인터, 구조체 및 de/referencing과 관련된 문제를 연구하고 있습니다. 각각의 의미가 각각 무엇인지에 대해 이해하고 각각을 초기화하는 것이 일반적이지만 프로그램에서 제대로 사용하지 않는 것 같습니다. 내가 가지고있는 것/잘 작동하지만, 이것들을 사용하는 더 좋은 방법이 있는지 알고 싶습니까?C++ 포인터 및 배열 ... [], * 및 &
일반적인 프로그램 요구 사항은 다음과 같습니다. (각 질문에 대해 생각하는 선을 포함 시켰습니다. 각 행을 프로그램에 올바르게 사용하고 통합하고 싶습니다.) 주로 사용 위치 StudentData[i].testArray
)
1 - 구조체를 사용하여 name, id #, test ( 포인터를 가리키는 포인터), 평균, 문자 등급을 저장하십시오.
struct StudentData {...};
2 - 학생의 수와 시험의 수 (각 학생을위한 동일)
3 요청 - 동적 구조의 배열을 할당
StudentData *allStudents;
allStudents = new StudentData[numStudents];
4 - 각 구조체의 Tests 구성원은 동적으로 할당 된 배열을 가리켜 야합니다. est 점수.
double *testsArray;
for (int i=0; i < numStudents; i++)
{
allStudents[i].testsArray = new double[numTests];
}
//does this need to be deleted with a for loop as well??
5 - 계산 시험 평균 성적 등급
6 - 디스플레이 정보
전체 코드 :
// Course Grade
// A program to gather and display a collection of student information.
// Programmer Name : Chuck
// C++ II
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//structure to hold data for each student
struct StudentData
{
string studentName;
int studentID;
double *testsArray; //pointer to an array of test scores
double testAverage; //calculated average test score
char courseGrade; //calculated course letter grade (A-F)
};
//function prototypes
string getName();
int getID();
double getScore(int count);
char calcGradeLetter(double *testAverage);
void displayData (StudentData allStudents[], int sCount);
int main()
{ cout << " Welcome to the Test Score Storer. This program will gather test\n";
cout << "scores for a given student name/id#. We'll start with some questions.\n\n";
int numTests;
cout << "How many test scores per student? : ";
cin >> numTests;
int numStudents;
cout << "How many students? : ";
cin >> numStudents;
cout << "Creating Database...";
//create array to hold all studentData structs
StudentData *allStudents;
allStudents = new StudentData[numStudents];
cout << "...";
//create a tests member array for each student struct
double *testsArray;
for (int i=0; i < numStudents; i++)
{
allStudents[i].testsArray = new double[numTests];
}
cout <<"...Done!\n";
system ("pause");
system ("CLS");
//TRYING
for (int i=0; i < numStudents; i++)
{
cout << "Student " << i+1 << " of " << numStudents << endl;
cout << "=================================\n";
allStudents[i].studentName = getName();
allStudents[i].studentID = getID();
double testTotal = 0.0;
for (int j=0; j < numTests; j++)
{
allStudents[i].testsArray[j] = getScore(j);
testTotal += allStudents[i].testsArray[j];
allStudents[i].testAverage = testTotal/numTests;
}
//calculate letter grade
allStudents[i].courseGrade = calcGradeLetter(&allStudents[i].testAverage);
cout << "Student, " << allStudents[i].studentName << ", completed.\n";
system ("pause");
system ("CLS");
}
//Display all collected student data in chart form
displayData(allStudents, numStudents);
delete [] allStudents;
system ("pause");
return (0);
}
//===========FUNCTIONS===========FUNCTIONS===========FUNCTIONS
string getName()
{
string name;
cout << "Student Name : ";
cin >> name;
return name;
}
int getID()
{
int IDnum;
cout << "Student ID : ";
cin >> IDnum;
return IDnum;
}
double getScore(int count)
{
double score;
score = -500;
while (score <0)
{ cout << "Test Score #" << count+1 <<" : ";
cin >> score;
if (score < 0)
{
cout << "Scores cannot be less than 0, try again.\n";
}
}
return score;
}
char calcGradeLetter(double *testAverage)
{
if (*testAverage >= 90) return 'A';
else if (*testAverage >= 80) return 'B';
else if (*testAverage >= 70) return 'C';
else if (*testAverage < 70) return 'F';
else return ('X');
}
void displayData(StudentData allStudents[], int sCount)
{
cout << "Student Data Chart:\n";
cout << "=================================================\n";
cout << "NAME ID# TEST AVE. GRADE\n";
for (int i = 0; i < sCount; i++)
{
cout << left << setw(18) << allStudents[i].studentName << " "
<< left << setw(12) << allStudents[i].studentID << " "
<< left << setw(11) << setprecision(4) << allStudents[i].testAverage << " "
<< allStudents[i].courseGrade << endl;
}
cout << "\nTable complete. ";
}
이 스택 내 첫 번째 게시물입니다, 죄송합니다.이 장소가 잘못된 장소에 있거나 숙제가 필요하다면 y, 나는 쉬운 대답만을 찾고있는 것이 아니다. 나는 새로운 개발자로서 열심히 배워야한다. 이 주제는 내가 작업하는데 많은 어려움을 겪고있는 것입니다.
동적 배열 인'new []'대신'std :: vector'를 사용하는 것이 훨씬 쉽습니다. – chris
단지 두 군데에서'std :; vector <> '를 사용하여이 cruft *가 얼마나 많이 사라지는 지 당신이 알고 있다면. 'std :: string','operator new()'및 콘솔 출력의 가짜 사용 외에 C 코드 일 수도 있습니다. 또한, 당신의'StudentData'는 생성자와 소멸자에 대해 * begging *입니다. – WhozCraig