C++ 将字符串添加到 const char* 数组

C++ Add string to const char* array

嘿,这可能是一个愚蠢的初学者问题。

我想从 const char* array[] 中的文件夹写入所有 .txt 文件的文件名。

所以我试着这样做:

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;

基本上,代码应该将 .txt 文件的文件名添加到 const char* locations 数组,但它不能使用追加,因为它给我错误:“C++ 表达式必须具有 class 类型但它的类型为“'const char *'”

那么我该怎么做才对呢?

问题:

  1. 您不能将项目附加到 C 数组 -T n[]- 因为数组的长度是在编译时确定的。
  2. 数组是指针(标量类型),不是对象,也没有方法。

解决方案:

最简单的解决方案是使用动态数组 std::vector

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

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

在你的例子中,一个名为 location 的字符串数组是 std::vector<std::string> locations
由于某些原因,C++ 容器不喜欢经典的 append(),并提供以下方法:

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

注意std::vector只提供push_backpop_back

参见: