c++实现一个函数输入文件路径,输出文件名

代码:

#include <iostream>  
#include <string>  
#include <cstring>

using namespace std;

void getFileName(string& path, string& fileName)  
{
    // 将路径字符串分割成文件名和文件路径两部分
    char* pos = strrchr(path.c_str(), '/');  
    if (pos == NULL)  
    {  
        // 如果路径中没有斜杠,则直接将文件名作为参数传递给输出函数
        fileName = path;  
        return;  
    }  
    else  
    {  
        pos++;  
    }  
    fileName = pos;  
}

int main()  
{
    string path;  
    string fileName;  
      
    cout << "请输入文件路径:";  
    cin >> path;  
      
    getFileName(path, fileName);  
      
    cout << "文件名:";  
    cin >> fileName;  
      
    return 0;  
}

猜你喜欢

转载自blog.csdn.net/weixin_55735677/article/details/130249314