主要的
#include <stdio.h>
#include "Student.h"
#include <stdlib.h>
void main()
{
Student* pStudents = new Student[0];
int arraySize = 0;
int input = 0;
while(input != 3)
{
printf("Press 1 to add student, 2 to print and 3 to quit.\n");
scanf_s("%d", &input);
switch(input)
{
case 1:
pStudents[numOfStudents].AddStudent(pStudents, arraySize);
arraySize++;
numOfStudents++;
break;
case 2:
break;
case 3:
break;
default:
printf("Invalid input\n");
break;
}
}
}
学生.h
#pragma once
#include <string>
#include <iostream>
using namespace std;
class Student
{
public:
Student(void);
~Student(void);
void AddStudent(Student* pStudent, int arraySize);
private:
string name;
int ID;
};
学生.cpp
#include "Student.h"
Student::Student(void)
: name("N/A")
, ID(0)
{
}
Student::~Student(void)
{
}
void Student::AddStudent(Student* pStudent, int arraySize)
{
if(arraySize == 0)
{
delete[] pStudent;
pStudent = NULL;
pStudent = new Student[1];
}
else
{
Student* temp = new Student[(arraySize+1)];
for(int i = 0; i < arraySize; ++i)
{
temp[i] = pStudent[i];
}
delete[] pStudent;
pStudent = temp;
}
printf("Enter name of student.\n");
cin >> name;
printf("Enter ID of student. \n");
cin >> ID;
}
好吧,我一直试图弄清楚这一点,但我做不到。我不确定自己做错了什么,但是当我尝试输入名称时,我不断收到写入违规。我试着查找答案,我看到的一些东西尝试使用向量,但我还没有被教导如何使用它们。
更新
主文件
void main()
{
Student* pStudents = new Student[100];
Student studentGenerator;
int numOfStudents = 0;
string name;
int ID;
int input = 0;
while(input != 3)
{
printf("Press 1 to add student, 2 to print and 3 to quit.\n");
scanf_s("%d", &input);
switch(input)
{
case 1:
printf("Enter name of student.\n");
cin >> name;
printf("Enter ID of student. \n");
cin >> ID;
studentGenerator = Student(name, ID);
pStudents[numOfStudents] = studentGenerator;
numOfStudents++;
break;
case 2:
for(int i = 0; i < numOfStudents; ++i)
{
studentGenerator.PrintStudents(pStudents[i]);
}
break;
case 3:
break;
default:
printf("Invalid input\n");
break;
}
}
}
学生.cpp
#include "Student.h"
Student::Student(void)
: name("N/A")
, ID(0)
{
}
Student::~Student(void)
{
}
Student::Student(string studentName, int studentID)
{
name = studentName;
ID = studentID;
}
void Student::PrintStudents(Student student)
{
cout << "Name: " << name << endl;
cout << "ID: " << ID << endl;
}