gpt4 book ai didi

c++ - 动态数组的大小与提交的值不匹配

转载 作者:太空狗 更新时间:2023-10-29 23:41:25 28 4
gpt4 key购买 nike

我正在学习动态内存,但有些地方不太对劲。我有一个接受数字作为输入的函数,并且应该生成一个该大小的数组。

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。

我完全迷惑了。

最佳答案

patientList->size() 等同于 patientList[0].size(),你的 patientList< 中初始字符串的长度 数组。在您刚刚分配数组的位置,结果始终为零;在其他情况下,它是第一个字符串的长度。

在 C++ 中制作容器的首选方法是 std::vectorstd::array。在您的情况下,使用 std::vector 更合适,因为您的代码动态分配了 patientList

关于c++ - 动态数组的大小与提交的值不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11479886/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com