Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problems using substr method

Status
Not open for further replies.

mrsnrub

Programmer
Mar 6, 2002
147
AU
Hello all,
I am very new to C++ and I am having a bit of difficulty using the substr function. I am trying to extract the filename without the extension from a string that contains the full filename and path. I have been trying to do the following:

string filename; // assigned a value in the constructor

and later...

int lastSlash = filename.find_last_of("\\");
int lastDot = filename.find_last_of(".");
int chars = lastDot - lastSlash;
string name = filename.substr(lastSlash, chars);

The 'filename' variable contains a valid string as I am managing to write to this file. I have also verified the values of 'lastSlash', 'lastDot' and 'chars' and these appear to be correct. However, the value that the field 'name' is receiving is '(null)'.

Can anyone explain what I may be doing wrong?

Many thanks in advance.
 
As is always the way - I have found the solution the moment I hit that submit button!!
For those who may be interested, the code I submitted was in fact working correctly - it was the way that I was writing the string to the file that was incorrect. I was using the fprintf function to write to the file and was leaving the string in std::string format. I had to convert it to a 'const char' type first.

 
Some addition - how about these names:
C:\mydir\mydoc.files\benz
or
theFile.ext
In 1st case dotpos < backslashpos, in 2nd backslashpos == string::npos...
Add more tobustness...
 
Thanks for the comments.
I have excluded the possibility of generating such filenames/paths in the way my original 'filename' (full path and filename) variable is generated.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top