Strange results in std::string.substr()

Hello everyone,

This is my first time posting and I'm happy to be here! I have not used C++ in a long time, however a project that I am involved with, has me writing quite a bit of C++ and my memory fails me at times! Here is my problem.

I am reading a file line by line into a string vector and then using the vector to creating several strings, used as properties in a class later on.

I'm using substr to grab only the data I need, and this is where the problem is.

Here is the code excerpt:

1
2
3
4
5
6
7
8
9
10
11
12
        int indexCh1;
	int indexCh2;

	indexCh1 = text_file[1].find("\"");
	indexCh2 = text_file[1].find("\"",3);

	strToName = text_file[1].substr(indexCh1+1, indexCh2-1);

	indexCh1 = text_file[1].find("<");
	indexCh2 = text_file[1].find(">");

	strToEmail = text_file[1].substr(indexCh1, indexCh2-1);


What I can't quite figure out, is why indexCh2-1 is not working. I have tried reducing the counter by one in the line before with indexCh2-- but with the same results. The actual full string looks like this:

["My Name" <myname@myname.com>]

The first substring results in My Name"
The second substring results in myname@myname.com>]

Always the indexCh1+1 and indexCh2+2 work, but never the -1.

Any idea's why this might be happening?

Thanks in advance,

Darren
Last edited on
The second param is the number of character you want to pull. It is not another position (like you seem to be thinking)

For example:

1
2
3
4
5
6
string foo = "0123456789";
string bar = foo.substr(2,3);

cout << bar;  // prints "234"
// the substring starts from position 2
//  and pulls 3 characters 
Ah that makes more sense, I seem to have misread the MSDN page for it!

Thanks for your help, much appreciated.

Darren
Topic archived. No new replies allowed.