Vinícius
Vinícius

Reputation: 15746

How to construct a CString/std::string from a string position

Given the following:

for( std::string line; getline( input, line ); )
{
        CString strFind = line.c_str();
        int n = strFind.ReverseFind( '\\' );

        CString s = CString( strFind,n );

        cout << s << endl;
      // m_Path.push_back( line.c_str() );  
}

It is reading a .ini configuration and on this .ini I have a line:

C:\Downloads\Insanity\Program\7. World.exe

this line is added to the vector<CString>.

My problem isint n = strFind.ReverseFind( '\\\' ); finds the string pos of the first \ searching from the end of the string to the beginning, after when constructing a CString like this CString s = CString( strFind,n ); I'm constructing the FIRST n characters on the string so s is equal C:\Downloads\Insanity\Program but what I want is to copy 7 .World.exe to the CString s and not the other way, how can I do that using CString or std::string?

Upvotes: 0

Views: 492

Answers (2)

Praetorian
Praetorian

Reputation: 109249

Are you converting the std::string to a CString only for the ReverseFind functionality? If so, you can use std::basic_string::find_last_of instead.

#include <iostream>
#include <string>

int main()
{
  std::string s(R"(C:\Downloads\Insanity\Program\7. World.exe)");

  auto pos = s.find_last_of( '\\' ) + 1; //advance to one beyond the backslash
  std::string filename( s, pos );
  std::cout << filename << std::endl;
}

Upvotes: 3

Reunanen
Reunanen

Reputation: 8031

How about:

CString s = strFind.Mid(n+1);

or:

std::string s = line.substr(n+1);

Upvotes: 2

Related Questions