简体   繁体   English

如何在给定文件路径的情况下获取具有文件扩展名的文件名并将其存储在 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?

I'm using Visual Studio 2019. The file path must be taken as an User input.我正在使用 Visual Studio 2019。文件路径必须作为用户输入。 I'm new to C++ and will appreciate any help i can get.我是 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM