I found the following example in a textbook - and adapted it to suit my needs. The problem is that I don't fully understand how it works, even after reading up on ::npos (English is not my first language).
Anyway, the code:
1 2 3
int i = name.rfind(".txt"); // integer i = ???
if (i == string::npos) // if i = ???
name.append(".txt");
So, what the code DOES is checks if the filename (in this context) ends with ".txt", if it does NOT, it appends ".txt" to the filename.
What I don't understand, and would appreciate if someone could shed some light on is this (in pseudo-code):
integer i = the value of a recursive search for ".txt" // I don't get it!
if integer i holds the value of... what, exactly?
Append ".txt" to the filename
Like I said, it works, but I'm not pleased with that, I want to learn too!
npos is just a token value that tells you that rfind did not find anything (probably -1 or something like that). rfind checks for the last occurence of the parameter string, and returns the index at which the parameter string begins.
So:
1 2 3 4 5
string name = "lol.txt";
int i = name.rfind(".txt");
//i holds the value 3 now, that's the index at which ".txt" starts
if (i==string::npos) //if ".txt" was NOT found - in this case it was, so this condition is false
name.append(".txt"); //append .txt at the end of the string