【问题标题】:c++ - BOOST filesystem path from variable stringc++ - 来自变量字符串的 BOOST 文件系统路径
【发布时间】:2017-02-15 21:45:54
【问题描述】:

我在创建boost::filesystem::path 对象(boost v1.55)时遇到了这个问题。我不知道如何从字符串变量或字符串串联创建路径?

//Example 1
namespace fs = boost::filesystem;
String dest = "C:/Users/username";  
fs::path destination (dest); //Error here

//Example 2
namespace fs = boost::filesystem;
String user = "username";
fs::path destination ("C:/Users/" + user); //Error here as well.

//Example 3
namespace fs = boost::filesystem;
fs::path destination ("C:/Users/username");

我只能在像上面的示例 3 那样在双引号之间指定整个字符串时创建路径对象,但这不允许变量输入。

基本上,我将如何使用 String 作为起点来实现 fs::path 对象类?

感谢您的帮助!

编辑

Link 用于提升/文件系统路径文档。重新学习 c++,所以其中的一些仍然让我有点头晕......我不太明白构造函数在这里是如何工作的......而且现在真的不知道该问什么......我' d绝对感谢任何指针。

【问题讨论】:

  • 那么,String 是什么?你怎么能把它变成文档所说的可以构造 path 的东西?你有String 的定义,你告诉我们。可能会要求它提供 C 字符串或 std::string 或其他东西。
  • 我正在重新学习 c++ ...我不完全记得/知道您所要求的 String 的“定义”。更新为包含文档链接...
  • 没有人知道String 是什么,请发帖MCVE
  • 显然没有人愿意详细说明,所以让我:String 不是标准的 C++ 类。有一个名为string(实际上是std::string)的类,以小写的“s”开头。看起来您的程序包含另一个名为String(大写“S”)的类。构造函数不起作用,因为您将这些 String 对象之一传递给它,它一无所知;你需要给它的是std::string
  • @RisaAudr 澄清一下,String您的代码 的一部分,而不是 C++ 语言的一部分。您应该能够在代码库中的某处找到定义。

标签: c++ boost-filesystem


【解决方案1】:

感谢 GManNickG - 你确实设法解决了我的问题。我正在使用 C++ builder 10.1,并且能够与 String 混淆一段时间,为其分配值等。实际上是 ShowMessage() method 导致我得到了我的答案 - 在 c++ builder 中,它想要AnsiString 参数可以工作,而 std::string 不会编译。 C++ Builder 10.1 将 String 定义为 AnsiString,而不是 std::string。同样,我对 c++ 很陌生,所以当 using namespace std 我没有意识到差异时(我对 Obj Oriented 的大部分先验知识都来自 java,您将字符串定义为 String

//Working Example in C++ Builder 10.1 Starter
namespace fs = boost::filesystem;
std::string un = "/username";
std::string dest = "C:/Users" + un;  //concatenation test
fs::path destination (dest); //Works, no compiler error now

std::string pathStdString = destination.string(); //retrieve 'dest' as std:string from path
String pathAnsiString = pathStdString.c_str(); //Converts std::string to ansi

ShowMessage(pathAnsiString); //Output box showing the path (valid in C++ Builder)

希望这可以帮助遇到类似问题的其他人。另外,link 说明 std::converts to Ansi 以防万一有人发现它有用。

【讨论】:

    猜你喜欢
    • 2020-06-28
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多