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