【问题标题】:Trying to convert <filesystem> output to a string尝试将 <filesystem> 输出转换为字符串
【发布时间】:2021-04-17 22:16:40
【问题描述】:

我可以使用其他方法在目录中加载带有文件名的向量,但我正在努力学习使用#include 。我不想打印到控制台,而是想将它添加到向量中。这听起来很简单,但我遇到了一个问题,即向量显然无法将文件系统输出识别为字符串。我不知道如何将其转换为字符串。

由于我无法直接将其推送到向量,因此我尝试将其发送到函数,但我得到的错误是“不存在从 const std::filesystem::path 到 std::string 的合适的用户定义转换。 "

我还尝试以各种可能的方式将 const auto& 文件更改为字符串,但没有成功。我只是无法让 vecArray 和 files.path() 成为相同的文件类型。

是否有可能使以下方法起作用,还是我需要改变整个方法?

#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
namespace fs = std::filesystem;

int main(){
    std::string directoryPath{};
    std::vector < std::string > vecArray{};
    getline(std::cin, directoryPath);
    for (const auto& files : fs::directory_iterator(directoryPath)) {
      vecArray.push_back(files.path());
    } 
    return 0;
}

【问题讨论】:

  • 这是阅读the documentation 并寻找转换为string 的机制的提示,其中的某些东西实际上是第二个“格式观察者”。
  • 谢谢稻田。我之前确实阅读过您发布的 ref,但 p.wstring() 没有深入了解。这需要我时间,但我正在逐渐适应 C++ 参考文档的语法。
  • tadman,我正在阅读您提供的 std::filesystem::path 的文档。我不知道什么是“格式观察者”。找到了一个链接,可以更清楚地了解它们。有点混乱(对我来说),但我想我正在弄清楚。谢谢。

标签: c++ c++11 visual-c++


【解决方案1】:

使用方法c_str()string()std::filesystem::path::string

vecArray.push_back(files.path().c_str());

或者

vecArray.push_back(files.path().string());

【讨论】:

  • 但如果不是 ascii 怎么办
【解决方案2】:

最好用
std::vector &lt;std::filesystem::path&gt; ..
或使用std::wstring。后者看起来不像代码那么简单

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2018-07-06
    • 2021-10-06
    • 2017-01-29
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多