【问题标题】:How to deal with spaces for boost::filesystem::path如何处理 boost::filesystem::path 的空格
【发布时间】:2017-04-21 19:42:31
【问题描述】:

我正在尝试从用户输入中获取一个目录并将其存储在来自 boost 库的路径对象中。当目录中没有空格时,这工作正常,例如C:\Windows\system32\file.exe 但是当尝试使用 C:\Program Files\file.exe 它不起作用时,程序就退出了。我正在考虑将输入作为字符串,然后对其进行操作以用转义字符替换空格。有没有更好的方法来做到这一点?

boost::filesystem::path path;
std::cout << "Please enter the path for the file you would like to hash:" << std::endl;
std::cout << "E.g. C:\\Program Files\\iTunes\\iTunes.exe" << std::endl;
std::cin >> path;   

然后将路径传递给函数以进行哈希处理。适用于没有空格但有空格的路径,程序刚刚退出。

std::string md5_file(boost::filesystem::path &file)
{
/* Takes a file and returns the md5 hash. */

// Create new hash wrapper
hashwrapper *myWrapper = new md5wrapper();
std::string hash;

// Hash file
try 
{
    hash = myWrapper->getHashFromFile(file.string());
}
catch (hlException &e) 
{
    std::cerr << "Error(" << e.error_number() << "): " << e.error_message() << std::endl;
}

// Clean up
delete myWrapper;
return hash;
}

【问题讨论】:

  • 更具体地说明究竟是什么坏了。 filesystem::path 处理空格没有问题。
  • 您的最小可编译示例在哪里,什么是“一切都中断了?”这是否包括显示器着火或整个街区断电?
  • 尝试使用getline 获取用户提供的整行
  • 我将支持getline 的建议。最重要的是,为什么myWrapper 被定义为指针?似乎您可以通过简单地创建一个本地堆栈变量来从该代码中获得等效的行为。将其委托给动态内存,使用裸指针,这似乎是在维护此代码时导致错误的一种简单方法。

标签: c++ boost path filesystems


【解决方案1】:

您的问题与 boost::filesystem::path 无关。您的输入有问题。如果路径中有空格,cin &gt;&gt; string_variable 将读取到第一个空格分隔符。

试着检查一下:

[boost::filesystem::path][1] path;
std::cout << "Please enter the path for the file you would like to hash:" << std::endl;
std::cout << "E.g. C:\\Program Files\\iTunes\\iTunes.exe" << std::endl;
std::cin >> path;
std::cout << path << endl;

输出应该是行C:\\Program

std::getline 读入带有空格的整个字符串:

string str;
getline(cin, s);
path = s;

【讨论】:

  • 我没有使用 std::cin ,而是将其更改为 std::getline(std::cin, string) ,现在我输入的任何内容都不起作用。我注意到这个变化的一个奇怪的事情是现在有两个神秘的引号输出到控制台。
  • @PrimateJunkie 对不起,我是getline(cin, s);
  • 原来 getline 不起作用,因为我在混合输入。之前有一个 int 输入,只需使用以下命令清除输入缓冲区: std::cin.ignore(std::numeric_limits<:streamsize>::max(), '\n') 还是谢谢!
猜你喜欢
  • 2016-06-02
  • 2012-07-06
  • 2011-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
  • 2011-04-23
  • 2018-02-18
相关资源
最近更新 更多