【问题标题】:Append the file extension in the file name if not given, in C++如果未给出,则在文件名中附加文件扩展名,在 C++ 中
【发布时间】:2021-08-29 20:11:14
【问题描述】:

我是C++ 的新手。我想将fileName 设为command line argument。用户必须输入fileName。如果用户输入的filename 没有文件extension,那么程序应该将extension 添加到fileName。 我正在C++ 中编写我的代码。有什么功能或者方法可以实现吗?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • ".ext" 文字添加到std::string 变量的实际问题是什么?!?您可以简单地使用+ 运算符。
  • 使用参数初始化一个std::basic_string,然后你可以使用std::basic_string::find_last_of来定位最后一个'.'(如果有的话),如果没有,只需附加新的扩展名。最重要的是,收藏cppreference.com 并使用它。它是 Internet 上最好的 C++ 参考资料。
  • 您可以使用它来确定是否有扩展并添加一个:https://en.cppreference.com/w/cpp/filesystem/path
  • @DavidC.Rankin: /some.directory/someFile 不是一个极端案例!这是一个完全正常的文件名。

标签: c++ command-line-arguments


【解决方案1】:
if (!(fileName.find_last_of('.') != std::string::npos)) {
    fileName.append(".ext");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-11
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 2023-01-24
    • 1970-01-01
    相关资源
    最近更新 更多