2017-04-21 111 views
0

我试图从用户输入中获取一个目录并将其存储在boost库中的路径对象中。当目录中没有空格时,这可以很好地工作,例如C:\ Windows \ system32 \ file.exe但是当试图使用C:\ Program Files \ file.exe时,它不起作用,程序刚刚退出。我正在考虑将输入作为字符串,然后对其进行操作以用换码符替换空格。有一个更好的方法吗?如何处理boost :: filesystem :: path的空格

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; 
} 
+3

更具体究竟是什么休息时间。 'filesystem :: path'没有处理空格的问题。 – Pavel

+3

你最小的可编译示例在哪里,什么是“一切都打破了?”这是否包括显示器着火或整个区块停电? –

+1

尝试使用'getline'获取用户提供的整个行 – AndyG

回答

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; 
+0

而不是使用std :: cin我已经将其更改为std :: getline(std :: cin,string),现在没有我键入的作品。我注意到一个奇怪的变化是现在有两个神秘的引号输出到控制台。 – PrimateJunkie

+0

@PrimateJunkie对不起,它是'getline(cin,s);' – Pavel

+0

原来getline没有工作,因为我混合了输入。有一个int输入前,只需要清除输入缓冲区:std :: cin.ignore(std :: numeric_limits :: max(),'\ n') 无论如何,谢谢! – PrimateJunkie

相关问题