目录迭代器值作为变量

时间:2019-04-01 13:41:39

标签: c++

我正在尝试将std:filesystem directory_iterator的输出转换为向量或变量。不断出错:no operator "=" matches these operands-操作数类型为:std::string = const std::filesystem

我真的是C ++的新手,这时碰壁了。以前我一直在使用系统命令,但将来希望避免使用它。

#include <string>
#include <iostream>
#include <filesystem>
#include <vector>
namespace fs = std::filesystem;
using namespace std;
int main()
{
    string objectInDirectory = "Jabberwocky";
    string dirlisted = "";
    for (const auto & entry : fs::directory_iterator(dirlisted)) {
        cout << "Next directory entry: " << entry.path() << endl;
        objectInDirectory = entry.path();
    }
    getchar();
}

1 个答案:

答案 0 :(得分:3)

entry.path() returns a const std::filesystem::path&。这不能隐式转换为std::string,因此您需要调用其字符串函数:

 objectInDirectory = entry.path().string();

无需转换为string;您可以将其分配给std::filesystem::path而不需要进行转换。这可能更理想,因为std::filesystem::pathstd::string有更好的内置路径处理工具