我正在尝试提取没有扩展名或限定路径的文件名,例如从/path/to/file.txt
中提取file
我有以下内容:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string temp = "dir/filename.txt";
auto bpos = temp.rfind('/')+1, epos = temp.rfind('.')-1;
cout << temp.substr(bpos,epos) << endl;
return 0;
}
输出是filename.tx
,我不确定为什么会出现这种情况。rfind()
就是找不到周期吗?转义字符也不起作用,输出相同。
std::string::substr
的第二个参数是字符数,而不是位置。
相反,你需要这样的东西:
temp.substr(bpos, epos - bpos + 1)
其计算给定2个位置的字符数。
这是一个演示。