Ошибка при попытке вернуть строковый массив в C ++ - PullRequest
0 голосов
/ 03 мая 2019

Я новичок, и теперь я изучаю все о массивах и экспериментирую с различными способами его реализации. На этот раз мне очень хотелось узнать, как вернуть строковый массив в c ++ без использования вектора для исследовательских целей. Я попытался реализовать указатели как способ возврата массива строк, но он дает мне ошибку времени выполнения, заявляющую, что строковый индекс находится вне диапазона. Будь добр, посоветуй, если я ошибся, вернув массив строк, и предложи лучшие решения для этого.

Вот код Employee.h:

    #pragma once
    #include<string>
    #include<iostream>

    class Employee
    {
    private:
    static const int recordSize = 100;
    static const int fieldSize = 4;
    std::string record[recordSize][fieldSize];

    public:
    Employee();
    ~Employee();
    std::string * employeeReadData();

    };

Вот это Employee.cpp

 Employee::Employee()
 {
 }

std::string * Employee::employeeReadData() {
std::ifstream inFile;
inFile.open("C:\\Users\\RJ\\Desktop\\employee-info.txt");

static std::string recordCopy[recordSize][fieldSize];

for (int index = 0; index < recordSize; index++) {
    for (int index2 = 0; index2 < fieldSize; index2++) {
        inFile >> record[index][index2];
    }
}

for (int index = 0; index < recordSize; index++) {
    for (int index2 = 0; index2 < fieldSize; index2++) {
        recordCopy[index][index2] = record[index][index2];
    }
}

inFile.close();

std::string * point = * recordCopy;

return point;
    }

Вот главная ():

    int main()
    {
    Employee emp;


    std::string* p = emp.employeeReadData();

    cout << p[0][0] <<endl;
    cout << p[0][1] << endl;
    cout << p[0][2] << endl;
    cout << p[0][3] << endl;

    return 0;
   }

работник-info.txt:

    ID           Firstname            Lastname                 Sales
     1             Reynard             Drexler             150000.00
     2              Joseph               Bones             250000.00

1 Ответ

1 голос
/ 03 мая 2019

предоставит лучшие решения для этого.

Ну, вы можете использовать методы, показанные в этом ответе , и обернуть массив в структуру внутри вашего Employee класса.

#include <string>

class Employee
{
   public:
       struct EmployeeRecord
       {
           static const int recordSize = 100;
           static const int fieldSize = 4;
           std::string record[recordSize][fieldSize];
       };
    private:           
       EmployeeRecord emp_record;

    public:           
       Employee() {}
       ~Employee() {}
       EmployeeRecord& employeeReadData();
};

Тогда в реализации:

 #include <fstream>

 Employee::Employee() {}

 Employee::EmployeeRecord& Employee::employeeReadData() 
 {
    std::ifstream inFile;
    inFile.open("C:\\Users\\RJ\\Desktop\\employee-info.txt");
    for (int index = 0; index < EmployeeRecord::recordSize; index++) 
    {
        for (int index2 = 0; index2 < EmployeeRecord::fieldSize; index2++) 
            inFile >> emp_record.record[index][index2];
    }
    return emp_record;
}

Тогда:

int main()
{
    Employee emp;
    auto& p = emp.employeeReadData(); // return reference to the struct that has the array

    std::cout << p.record[0][0] << std::endl;
    std::cout << p.record[0][1] << std::endl;
    std::cout << p.record[0][2] << std::endl;
    std::cout << p.record[0][3] << std::endl;
    return 0;   
}

Нет использования указателей, а также нет использования векторов. Это почти так же просто, как вы можете получить без использования указателей.

...