【问题标题】:appending a file extension in a C++ progam在 C++ 程序中附加文件扩展名
【发布时间】:2014-09-07 12:50:09
【问题描述】:

我正在编写一个 C++ 程序,使用 ifstream ofstream 函数。我问用户要打开哪个文件,然后问他们给文件取什么名字。请看下面的代码,帮助我弄清楚如何正确使用 append 函数。

cout << "Please type the new name for your file ( File must end in '.txt'): ";
cin>>outf; // stores name of requested txt file
if (!outf.rfind(".txt"))
{
 outf.append(".txt");
}

可以使用建议....

【问题讨论】:

    标签: c++ append


    【解决方案1】:

    首先你需要一个函数来询问字符串是否以“.txt”结尾。 outf.rfind(".txt") 会在字符串中找到字符串“.txt”anywhere。 (rfind()find() 的不同之处在于它从末尾开始搜索,但它可以在字符串中的任何位置找到匹配项。)

    bool ends_with(std::string const & str, std::string const & suffix)
    {
        // If the string is smaller than the suffix then there is no match.
        if (str.size() < suffix.size()) { return false; }
    
        return 0 == str.compare(str.size() - suffix.size(),
                                suffix.size(),
                                suffix,
                                0,
                                suffix.size());
    }
    

    现在我们可以使用std::string+= 运算符重载如果此函数返回false 附加到字符串:

    if (!ends_with(outf, ".txt")) {
        outf += ".txt";
    }
    

    (See a live demo.)

    【讨论】:

    • 感谢您的帮助。查看您的个人资料,我可以看到您拥有整个世界的知识,因此非常感谢您对我的帮助。因为我对 C++ 编程有点陌生,所以我不能完全理解你在这里放的所有东西......但你的回答确实让我朝着正确的方向前进,而且不那么复杂。请看我的回答
    • @Jeremy 不幸的是,您的方法仍然不正确。如果您需要帮助理解我的答案,请在此处提问。我们可以转到 SO 聊天,我很乐意澄清任何事情。
    【解决方案2】:

    上一个答案让我朝着正确的方向前进,这对我正在寻找的东西很有用......希望这可以帮助其他人寻找同样的东西。

    cout << "Please type the new name for your file ( File must end in '.XML'): ";
    cin>>outf; // stores name of requested xml file
    
    string y=".xml";
    if (outf.rfind(".xml")!= true)
    {
        outf.append(y);
    }
    

    【讨论】:

    • 现在试试outf = "a.txt.zip";。您不会附加.txt,因为名称包含.txt——但它不在末尾!这就是为什么您需要在我的回答中使用 ends_with() 函数。
    • 我今天早上实际上发现了这个缺陷......当时我不小心将错误的扩展名添加到文件中。我重新查看了您的答案,然后注意到您添加的现场演示......再次感谢您,感谢您的耐心...
    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多