尝试在C ++中返回字符串数组时遇到错误

时间:2019-05-03 03:17:25

标签: c++ arrays object multidimensional-array

我是一个初学者,现在正在学习有关数组的所有知识,并尝试各种不同的方法来实现它。这次,我真的很想知道如何在不使用vector进行研究的情况下用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;
    }

这是main():

    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;
   }

employee-info.txt:

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

1 个答案:

答案 0 :(得分:1)

  

为此提供更好的解决方案。

好吧,您可以使用this answer中显示的技术,并将数组包装到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;   
}

没有使用指针,也没有使用向量。这几乎就像不使用指针一样简单。