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

use*_*853 2 c++ arrays dynamic

我正在学习动态记忆,但事情并不顺利.我有一个函数接受一个数字作为输入,并应该生成一个这样大小的数组.

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];
}
Run Code Online (Sandbox Code Playgroud)

(第3代码块中最相关的代码).

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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试显示列表的内容.

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;
}
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,我提交的数字大小不是数组的大小.例如,在fillOut()我有函数输出大小.它每次输出的大小为0.然后listPatients(),我有一些东西再次打印尺寸,以验证我做得对.如果我最初输入3,则在此功能中输出5.

我完全神秘了.

das*_*ght 6

该行patientList->size()等效patientList[0].size()patientList数组中初始字符串的长度.刚刚分配了数组,结果总是为零; 在其他情况下,它是第一个字符串的长度.

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