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

标签 c++ arrays append

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

我想写入 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* 位置数组中,但使用追加不起作用,因为它给了我错误:“C++ 表达式必须具有类类型,但它具有类型 '' const char *''"

那么我该如何做才是正确的呢?

最佳答案

问题:

  1. 您无法将项目 append 到 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

参见:

关于C++ 将字符串添加到 const char* 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70229531/

相关文章:

c++ - eclipse CDT : How to manage multiple main() functions in a single C++ project?

c++ - 有效地向字符串 append 或插入可变数量的空格

javascript - 无法将数据 append 到 Div 并重定向页面

php - 逗号后加空格

php - 使用 AJAX 从二维 PHP 数组创建二维 jQuery 数组

c - C 字符数组中的字符串终止符

python - 如何将一行 append 到另一个数据框

c++ - 如何在 C++ 中输入空间?

c++ - JDK9 Hotspot debug using gdb, causing SIGSEGV Segmentation fault in eclipse/Ubuntu 终端

c++ - 无法将参数 1 从 int 转换为 int && 错误