如何在给定文件路径的情况下获取带有文件扩展名的文件名并将其存储在 C++ 控制台应用程序中的字符串中?
How do you get a file name with the file name extension given the file path and store it in a string in C++ Console Application?
我正在使用 Visual Studio 2019。文件路径必须作为用户输入。我是 C++ 的新手,非常感谢我能得到的任何帮助。
#include <iostream>
#include <string>
int main()
{
std::string filename;
std::cout << "Enter file path: ";
std::cin >> filename; // "Example: C:/test/file1.txt"
// Remove directory if present.
// Do this before extension removal incase directory has a period character.
const size_t last_slash_idx = filename.find_last_of("\/");
if (std::string::npos != last_slash_idx)
{
filename.erase(0, last_slash_idx + 1);
}
std::cout << filename;
return 0;
}
我正在使用 Visual Studio 2019。文件路径必须作为用户输入。我是 C++ 的新手,非常感谢我能得到的任何帮助。
#include <iostream>
#include <string>
int main()
{
std::string filename;
std::cout << "Enter file path: ";
std::cin >> filename; // "Example: C:/test/file1.txt"
// Remove directory if present.
// Do this before extension removal incase directory has a period character.
const size_t last_slash_idx = filename.find_last_of("\/");
if (std::string::npos != last_slash_idx)
{
filename.erase(0, last_slash_idx + 1);
}
std::cout << filename;
return 0;
}