嘿,这可能是一个愚蠢的初学者问题。
我想写入 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 *''"
那么我该如何做才是正确的呢?
最佳答案
问题:
- 您无法将项目 append 到 C 数组 -
T n[]
- 因为数组的长度是在编译时确定的。 - 数组是一个指针(它是标量类型),它不是对象并且没有方法。
解决方案:
最简单的解决方案是使用 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_back
和pop_back
参见:
关于C++ 将字符串添加到 const char* 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70229531/