The logic of ::npos?

Hello all!

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!

Thanks for reading this,

HMW
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 
Last edited on
Aah... I think I get it, but just to be on the safe side; in your example, i holds the value 3 because the count goes like:

1
2
lol.txt
0123456

Therefore 3 is where the dot (.) in ".txt" starts, am I thinking correctly so far?

Further:
1
2
if (i == -1) // Where -1 is indeed ::npos, correct?
  name.append(".txt")


Thanks, I appreciate it!

HMW
Yes, you got that right.
Yes, you got that right.

Thank you again for your effort.

Sincerely,

HMW
Topic archived. No new replies allowed.