无法创建光栅堆栈,因为我无法连接字符串(dir_name + 文件名)

Cannot create a raster stack, because I cannot concatenate strings (dir_name + filename)

我正在玩 C++ 和 GDAL,做一些基本练习。我想要构建的其中一件事是创建一个程序,该程序从目录名称中读取其中的文件,然后在 foor 循环中读取数据集并将波段写入新的虚拟栅格。我设法使用 boost 库从目录中读取文件。但是,当我想创建光栅时,它说找不到文件名。我想通过创建一个名为 bdir 的新变量来解决这个问题,然后连接文件名,这样我就可以将它传递给 GDALOpenShared 函数。

这是我的代码,因此您可能对我想要完成的事情有更好的了解:

#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include "gdal/gdal.h"
#include "gdal/cpl_conv.h" /* for CPLMalloc() */
#include "gdal/vrtdataset.h"
#include <iostream>
#include <string>
#include "gdal/cpl_string.h"
#include <stdbool.h>


using namespace std;
using namespace boost::filesystem;

int main()
{
    GDALAllRegister();

    path p("/home/roger/Documents/09_Stack_Raster/media");
    GDALDriver *poDriver = (GDALDriver*) GDALGetDriverByName( "VRT" );
    GDALDataset *poSrcDS, *poVRTDS;
    string bdir = "media/";

    for (auto i = directory_iterator(p); i != directory_iterator(); i++)
    {   
        string filename = i -> path().filename().string();
        cout << filename << endl;
        if (!is_directory(i->path()) && boost::ends_with(filename, ".tif"))
        {
            cout << i->path().filename().string() << endl;
            std::string str = "media/" + i->path().filename().string().c_str();
            poSrcDS = (GDALDataset *) GDALOpenShared(i->path().filename().string().c_str(), GA_ReadOnly);
            poVRTDS = poDriver->CreateCopy("media/B02_stack.vrt", poSrcDS,FALSE,NULL,NULL,NULL);
            GDALClose((GDALDatasetH) poSrcDS);
        }

        else
            continue;
    }

    GDALClose((GDALDatasetH) poVRTDS);

}

但是我收到以下错误:

stack_raster.cpp: In function 'int main()':
stack_raster.cpp:33:40: error: invalid operands of types 'const char [7]' and 'const char*' to binary 'operator+'
std::string str = "media/" + i->path().filename().string().c_str();

有人可以帮我吗?我检查了这个答案 Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

建议为了确保字符串连接在 C++ 中有效,两个参数都应该是字符串,这是我通过将 bdir 声明为字符串并使用 .[= 添加从 char 到字符串的转换来实现的。 28=]() 路径迭代器中的方法。

有人可以给我一些提示吗?

std::string str = "media/" + i->path().filename().string().c_str();

这不会编译,因为 + 运算符的两个操作数都是 const char* 类型 [1](有时称为 "C strings"),而不是 std::string 类型.

从第二个操作数中删除最后的 .c_str()(这是不必要的,因为您想连接 std::string,而不是 C 字符串版本),它应该可以工作。

[1] 从技术上讲,第一个操作数是 const char [7] 类型,它与 const char* 完全 不同,但出于本文的目的问题重要的是这些类型不能使用 + 运算符连接。