Home > Net >  Trying to copy lines from text file to array of strings (char**)
Trying to copy lines from text file to array of strings (char**)

Time:06-15

This is my code for allocating memory for the array of strings:

FileReader::FileReader()
{
    readBuffer = (char**)malloc(100 * sizeof(char*));

    for (int i = 0; i < 100; i  )
    {
        readBuffer[i] = (char*)malloc(200 * sizeof(char));
    }
}

Im alocating 100 strings for 100 lines then allocating 200 chars for each string.

This is my code for reading the lines:

char** FileReader::ReadFile(const char* filename)
{
    int i = 0;

    File.open(filename);

    if (File.is_open())
    {
        while (getline(File, tmpString))
        {
            readBuffer[i] = (char*)tmpString.c_str();
            i  ;
        }
        return readBuffer;
    }
    
}

and for printing:

for (int i = 0; i <= 5; i  )
    {
        cout << fileCpy[i];
    }

this is the output to terminal: Picture

As you can see it just repeats the last line of the file as the file just reads: This is test line 2 line 3 line 4 line 5

Any idea on whats going on? Why the lines aren't copying correctly?

CodePudding user response:

Replace

readBuffer[i] = (char*)tmpString.c_str();

with

strcpy(readBuffer[i], tmpString.c_str());

Your version just saves a pointers to tmpString in your array. When tmpString changes then that pointer points at the new contents of tmpString (at that's just the best possible outcome). However strcpy actually copies the characters of the string, which is what you want.

Of course, I'm sure it doesn't need saying, but you can avoid all the headache and complication like this

vector<string> readBuffer;

This way there are no more pointer problems, no more manual allocation or freeing of memory, no limits, you aren't limited to 100 lines or 200 characters per line. I'm sure you have a reason for doing things the hard way. but I wonder if it's a good reason.

CodePudding user response:

First of all, you have to switch from C to C .

Do not allocate memory like that when the only way to do it now in modern C is trough smart pointers from the memory header.

Anyways, you do not directly need dynamic allocation here. You have to encapsulate your data within the class and to use the std::vector<std::string> component from the standard library. This vector is a dynamic array that handle all the memory stuff behind the scene for you.

To read all lines of a file :

std::string item_name;
std::vector<std::string> your_buffer;
std::ifstream name_fileout;

name_fileout.open("test.txt");

while (std::getline(name_fileout, item_name))
{
    your_buffer.push_back(item_name);
    std::cout << item_name;
}

name_fileout.close();
  • Related