简体   繁体   English

在C ++程序中附加文件扩展名

[英]appending a file extension in a C++ progam

I am writing a C++ program, using the ifstream ofstream functions. 我正在使用ifstream ofstream函数编写C ++程序。 I ask the user which file to open, and then ask them what to name the file. 我问用户要打开哪个文件,然后问他们如何命名该文件。 Please look at the code below and help me figure out how to use the append function properly. 请查看下面的代码,帮助我弄清楚如何正确使用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");
}

could use suggestions.... 可以使用建议...。

First you need a function to ask if the string ends with ".txt". 首先,您需要一个函数来询问字符串是否以“ .txt”结尾。 outf.rfind(".txt") will find the string ".txt" anywhere in the string. outf.rfind(".txt")将在字符串中的任何位置找到字符串“ .txt”。 ( rfind() differs from find() in that it starts searching from the end, but it can find a match anywhere in the string.) 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());
}

Now we can just use std::string 's += operator overload to append to the string if this function returns false: 现在,如果此函数返回false,我们就可以使用std::string+=运算符重载附加到字符串上:

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

( See a live demo .) 请观看现场演示 。)

the Previous answer set me in the right direction, and this worked for what I was looking for...hopefully this helps someone else looking for the same thing. 先前的答案使我朝着正确的方向发展,这对我一直在寻找的东西有用...希望这可以帮助其他人寻找相同的东西。

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);
}

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

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