简体   繁体   中英

appending a file extension in a C++ progam

I am writing a C++ program, using the ifstream ofstream functions. 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.

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". outf.rfind(".txt") will find the string ".txt" anywhere in the string. ( rfind() differs from find() in that it starts searching from the end, but it can find a match anywhere in the string.)

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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