Search code examples
c++qtstdstringqstring

Inserting string in another string at specific index c++/Qt


I have a QString (it may does not matter since I convet it to std::string anyway) which contains the full unix path to a file. e.g. /home/user/folder/name.of.another_file.txt.

I want to append another string to this file name right before the extension name. e.g. I pass to the function "positive", here I call it vector_name and at the end I want to get /home/user/folder/name.of.another_file_positive.txt (note that the last underscore should be added by the function itself.

Here is my code but it does not compile, unfortunately!!

QString temp(mPath); //copy value of the member variable so it doesnt change???

std::string fullPath = temp.toStdString();
std::size_t lastIndex = std::string::find_last_of(fullPath, ".");
std::string::insert(lastIndex, fullPath.append("_" + vector_name.toStdString()));

std::cout << fullPath;

I get the following errors:

error: cannot call member function 'std::basic_string<_CharT, _Traits, _Alloc>::size_type std::basic_string<_CharT, _Traits, _Alloc>::find_last_of(const std::basic_string<_CharT, _Traits, _Alloc>&, std::basic_string<_CharT, _Traits, _Alloc>::size_type) const [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::basic_string<_CharT, _Traits, _Alloc>::size_type = long unsigned int]' without object
         std::size_t lastIndex = std::string::find_last_of(fullPath, ".");

cannot call member function 'std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::insert(std::basic_string<_CharT, _Traits, _Alloc>::size_type, const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::basic_string<_CharT, _Traits, _Alloc>::size_type = long unsigned int]' without object
     std::string::insert(lastIndex, fullPath.append("_" + vector_name.toStdString()));

P.S. I would really appriciate if you also can tell me how can I achieve this using QString or Qt library itself!


Solution

  • The reason for the error is that find_last_of and insert are member functions of std::string, not static or non-member functions. Therefore you need an object to access the function.

    The corrections are below:

    std::size_t lastIndex = fullPath.find_last_of(".");
    fullPath.insert(lastIndex, "_" + vector_name.toStdString());
    cout << fullPath;
    

    Live Example using dummy data

    Also, you may want to test the return values of those function calls. What if there is no "." in the file name?