I'm a beginner and I'm now learning all about arrays and experimenting different ways to implement it. This time, I really wanted to know how to return a string array in c++ without using vector for research purposes. I tried implementing pointers as a way to return a string array but it is giving me a runtime error stating that the string subscript is out of range. Kindly advice if I made the wrong way of returning the string array and provide better solutions for this.
Here is the code the 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();
};
Here is the 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;
}
Here is 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
std::arrayor some class that wraps the array concept. I guess that ends the research.Employee::Employee(). Also, declaringstatic std::string recordCopymight let you get away with returning the address (since it's static) but you might want to find a better way to do it.