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:
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?
CodePudding user response:
Problem:
- You can't append items to a C array -
T n[]
- because the length of the array is determined at compile time. - 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<std::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: