我正在学习动态记忆,但有些事情不太对劲。我有一个接受数字作为输入的函数,并且应该创建一个该大小的数组。
class Doctor {
public:
Doctor();
void fillOut();
void listPatients();
void patientReset();
~Doctor();
private:
string name;
int numPatients;
string *patientList;
};
Doctor::Doctor() {
name = "";
numPatients = 0;
patientList = new string[numPatients];
}
(第三个代码块中最相关的代码)。
void Doctor::fillOut()
{
string buffer = "";
string buffer2 = "";
size_t found;
bool valid = false;
int numP = 0;
int tester = 0;
bool validNum = false;
while(!valid)
{
cout << "Enter doctor name: ";
getline(cin, buffer);
found = buffer.find_first_of("1234567890!@#$%^&*()-=_+/<>?;':][");
if(string::npos == found)
{
name = buffer;
valid = true;
}
}
while (!validNum)
{
cout << "\nEnter number of patients: ";
buffer = "";
getline(cin, buffer);
buffer2 = buffer;
stringstream ss(buffer);
if(ss >> tester)
{
stringstream ss2(buffer2);
ss2 >> numP;
validNum = true;
}
else
{
cout << "Not a number. Please try again." << endl;
}
}
patientList = new string[numP];
cout << patientList->size() << endl;
for(int i = 0; i < (numP + 0); i++)
{
valid = false;
while(!valid)
{
cout << "\nEnter patient " << (i + 1) << ": ";
getline(cin,buffer);
found = buffer.find_first_of("1234567890!@#$%^&*()-=_+,./<>?;':][");
if(string::npos == found)
{
*(patientList + i - 0) = buffer;
//patientList[i-1] = buffer;
valid = true;
}
else
{
valid = false;
}
}
}
}
然后我尝试显示列表的内容。
void Doctor::listPatients()
{
cout << "size: " << patientList->size() << endl;
cout << "\nDoctor: " << name << endl;
for(int i = 0; i < (patientList->size() - 1); i++)
{
cout << "Patient " << (i+1) << ": " << patientList[i] << endl;
}
cout << "end patients" << endl;
}
但由于某种原因,我提交的大小不是数组的大小。例如,在fillOut()
我有函数输出大小。它每次输出大小为0。然后在 中listPatients()
,我有一些东西可以再次打印尺寸,以验证我做对了。如果我最初输入 3,它在此函数中输出 5。
我完全迷惑了。