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

时间:2017-04-21 19:42:32

标签: 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;
}

1 个答案:

答案 0 :(得分:2)

你的问题与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;