c++ - 如何处理 boost::filesystem::path 的空格

标签 c++ boost path filesystems

我正在尝试从用户输入中获取目录并将其存储在 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;
}

最佳答案

您的问题与 boost::filesystem::path 无关。您的输入有问题。如果路径有空格 cin >> 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;

关于c++ - 如何处理 boost::filesystem::path 的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43550799/

相关文章:

c++ - 十六进制编辑 dll 以更改依赖项名称?

c++ - 使用 Boost Hana 反射(reflect) C 风格数组

c++ - boost 日期时间解析字符串

node.js - Node.js 中的文件系统与路径模块

c++ - 在 C++ 中使用 setw 和 setprecision 时如何显示带有值的 $ 符号

c++ - 在函数调用中更新静态成员会导致崩溃

c++ - 在 Win32 程序中使用 XAML 托管 API 导航到页面会导致访问冲突

c++ - 扩展 boost::lexical_cast 用于其他类数据类型

url - 为什么 require.js 忽略配置 baseUrl 和路径

c# - 项目文件的文件路径?