c++如何从string类型中获取图片名字
时间: 2023-07-15 15:11:49 浏览: 85
如果你的字符串中只包含图片名字,可以使用以下代码从字符串中获取图片名字:
```c++
#include <string>
int main() {
std::string str = "example.png";
std::string filename = str.substr(0, str.find_last_of("."));
return 0;
}
```
这个代码使用`substr`函数和`find_last_of`函数从字符串中获取文件名。`substr`函数用于获取子串,`find_last_of`函数用于查找最后一个`.`字符的位置,以便提取文件名。在这个例子中,获取到的文件名为`example`。
如果你的字符串中包含完整的文件路径,可以使用以下代码从字符串中获取图片名字:
```c++
#include <string>
#include <filesystem>
int main() {
std::string str = "C:/example/example.png";
std::string filename = std::filesystem::path(str).filename().string();
filename = filename.substr(0, filename.find_last_of("."));
return 0;
}
```
这个代码使用`std::filesystem::path`函数从字符串中获取文件名。`filename`函数用于获取文件名,以便提取文件名。在这个例子中,获取到的文件名为`example`。需要注意的是,这个代码需要使用C++17或更高版本。