如何处理 boost::filesystem::path 的空格

How to deal with spaces for boost::filesystem::path

我正在尝试从用户输入中获取目录并将其存储在 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无关。您的输入有问题。如果路径有 spaces cin >> string_variable 将读取到第一个白色-space 分隔符。

尝试检查一下:

[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 使用 spaces:

读取整个字符串
string str;
getline(cin, s);
path = s;