【问题标题】:C++ Add string to const char* arrayC++ 将字符串添加到 const char* 数组
【发布时间】:2022-01-10 17:16:56
【问题描述】:

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

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

那我该怎么做呢?

【问题讨论】:

  • 简答:使用std::vector&lt;std::string&gt;
  • 嘿@Brian 你想让我改用 std::vector<:string> 吗?我需要 const char* locations[] 格式的数组列表框。我将如何转换?尝试使用 std::vector<:string>locations;和位置.push_back(FindFileData.cFileName);现在。我怎样才能把它变成一个数组?
  • 使用向量。然后locations[ i ].data() 会将char* 指针返回到std::string 的底层缓冲区。

标签: c++ arrays append


【解决方案1】:

问题:

  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&lt;std::string&gt; 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

见:

【讨论】:

  • 数组不是指针。
  • @Peter 一个数组一个指向elements × 1 element size长度内存块的指针。 int a[5]; std::cout &lt;&lt; a &lt;&lt; std::endl; 也会打印一个地址。
  • 一个数组可以转换为一个指针(指向它的第一个元素),但是有些不同。假设一个数组是一个指针工作时,有一些上下文,而其他一些则失败。如果您说的是真的,那么此链接中的讨论将毫无意义。 stackoverflow.com/questions/1461432/…
猜你喜欢
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
  • 2018-10-03
  • 2010-09-21
  • 2022-01-13
相关资源
最近更新 更多