[英]Get extension std::out_of_range error
這段代碼有什么問題? 還有另一種方法嗎? 它不斷拋出std :: out_of_range錯誤。
std::wstring ext(FileInformation.cFileName);
ext = ext.substr(ext.find(L"."));
出問題的是,您沒有處理文件沒有擴展名的情況。
發生的情況是ext.find(L".")
返回std::wstring::npos
(可能的最高數字-表示“未找到”),因為它找不到點。
然后,您將調用ext.substr(std::wstring::npos)
,這當然超出了范圍。
您必須檢查這種情況:
std::wstring ext(FileInformation.cFileName);
std::size_t dotPos = ext.find(L".");
if(dotPos != std::wstring::npos) {
ext = ext.substr(dotPos);
} else {
ext = L"."; // assuming you want to treat an empty extension like this
}
但是,如果您的目標是提取文件擴展名,則需要注意一些其他問題:
file.ab
的文件提供.ab
,而Windows會將文件擴展名視為.b
。 因此,您可能需要使用rfind
而不是find
,它向后搜索。 file.hello world
:文件擴展名不能包含空格( file.hello world
是不帶擴展名的文件),因此您也需要檢查一下... 因此,由於您顯然已經在使用WinAPI,因此建議您使用完全用於此目的的WinAPI函數: PathFindExtension
。 這樣,您就不會出錯。
示例(假設您仍然需要一個點-否則將其刪除):
ext = std::wstring(L".") + *PathFindExtension(ext.c_str());
另外,還有一個boost
庫,它也可以使用boost::path::extension
來提取文件擴展boost::path::extension
,但是它有點繁重,如果您還沒有使用boost
,那么就不值得考慮了。
不能有“。”。 在FileInformation.cFileName
, find
將返回std::wstring::npos
因此首先檢查find
的返回,然后調用substr
。
也許是這樣的:
std::wstring ext(FileInformation.cFileName);
std::size_t found=ext.find(L".");
if (found!=std::wstring::npos)
ext = ext.substr(found);
FileInformation.cFileName不包含點,則find()將返回string :: npos。
因此,在使用substr之前,首先需要檢查string :: npos,因為如果substr的第一個參數大於字符串長度,則會拋出out_of_range。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.