[英]appending a file extension in a C++ progam
我正在使用ifstream ofstream函数编写C ++程序。 我问用户要打开哪个文件,然后问他们如何命名该文件。 请查看下面的代码,帮助我弄清楚如何正确使用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");
}
可以使用建议...。
首先,您需要一个函数来询问字符串是否以“ .txt”结尾。 outf.rfind(".txt")
将在字符串中的任何位置找到字符串“ .txt”。 ( 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());
}
现在,如果此函数返回false,我们就可以使用std::string
的+=
运算符重载附加到字符串上:
if (!ends_with(outf, ".txt")) {
outf += ".txt";
}
( 请观看现场演示 。)
先前的答案使我朝着正确的方向发展,这对我一直在寻找的东西有用...希望这可以帮助其他人寻找相同的东西。
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.