Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Add string to const char* array

Hey so this is probably a dumb beginner question.

I want to write the filename of all .txt files from a folder inside a const char* array[].

So I tried to do it like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const char* locations[] = {"1"};
bool x = true;
int i = 0;    

LPCSTR file = "C:/Folder/*.txt";
WIN32_FIND_DATA FindFileData;

HANDLE hFind;
hFind = FindFirstFile(file, &FindFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
    do 
    {
        locations.append(FindFileData.cFileName); //Gives an error
        i++;
    }
    while (FindNextFile(hFind, &FindFileData));
    FindClose(hFind);
}
cout << "number of files " << i << endl;

Basically the code should add the Filename of the .txt file to the const char* locations array but it doesn’t work using append as it gives me the error: "C++ expression must have class type but it has type ”const char *”"

So how do I do it right?

>Solution :

Problem:

  1. You can’t append items to a C array –T n[]– because the length of the array is determined at compile time.
  2. An array is a pointer(which is a scalar type), which isn’t an object and doesn’t have methods.

Solution:

The easiest solution is to use an std::vector which is a dynamic array:

#include <vector>
// ...
std::vector<T> name;

// or if you have initial values...
std::vector<T> name = {
    // bla bla bla..
};

In your case an array called location of strings is std::vector<string> locations.
For some reason, C++ containers don’t like the classical append(), and provide the following methods:

container.push_back();  // append.
container.push_front(); // prepend.
container.pop_back();   // remove last
container.pop_front();  // remove first

Note that std::vector only provides push_back and pop_back

See:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading