Search code examples
c++indexingstdstring

extracting a file name from file path in c++


I have a string storing path of a file and I'm doing some string processing, indexing of a std::string object, but output string is strange, code:

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string x = "C:\\Users\\lenovo\\Desktop\\QBFdata.txt";
    string temp = "";
    for(int  i = x.length() - 1; i > 0; i--)
    {
        if(x[i] == '\\')
            break;
        else
            temp.append(&x[i]);
    }
 cout << temp << "\n";
}

but output is strange apparently it append the contents of temp again to it.

txttxt.txta.txtta.txtata.txtdata.txtFdata.txtBFdata.txtQBFdata.txt

Please don't suggest any alternatives to this because I already have a solution

int main()
{
    string x = "C:\\Users\\NK\\Desktop\\QBFdata.txt";
    int pos = x.find_last_of('\\');
    string temp = x.substr(pos + 1);
    cout << temp;
}

It works fine.

I want to know what is the problem in the first code.

Thanks.

I'm using codeblocks 16.01


Solution

  • As others have stated, the problem is that you are using the wrong overload of std::string::append(), so you are appending whole substrings, not individual characters, on each loop iteration.

    To append a single character at a time, use one of these instead:

    temp.append(&x[i], 1);
    

    temp.push_back(x[i]);
    

    temp += x[i];
    

    However since you are looping backwards, you need to prepend each character in the FRONT of the string instead of append to the BACK:

    temp.insert(0, &x[i], 1);
    

    temp = x[i] + temp;