D-Antonio D-Antonio - 1 year ago 107
C++ Question

How to substract a specifiek text from a string with the function substring

In order to substract a timestamp from my string i am using substring( pos,#char).

My code works partially. The problem that i have is consistency.
I am retrieving a string from a textfile in the format "Name Time" ,
Example : "Don 00:12".

this string is extracted from the file into HighScoreInfo1.
Also from a different file i am extracting a string, which is the name part, into previous_name.

With this information i am trying to calculate the position where the substring has to start.

int test = HighScoreInfo1.size() - (previous_name.size()+1 );

i already took measures for the extra char which is a space, thats the +2.
1 for the space and 1 to get to the position where he needs to start.

the timestamp, 00:00, is five characters long.

int test = HighScoreInfo1.size() - (previous_name.size()+2 );
TimeToBeat = HighScoreInfo1.substr(test, 5);
TestFile << "Orginal string size " << ">>" << HighScoreInfo1.size() << " " << "size of name"<< ">>" <<previous_name.size()+2<<" " << "Position "<< test << endl;
TestFile << "Orginal string " << ">>"<<HighScoreInfo1 << " " << "Substring"<< ">>" <<TimeToBeat << endl;

this is my output with a long name:

Orginal string size >>14 size of name>>10 Position >> 4
Orginal string >>Chrystel 00:09 Substring>>stel

Sidenote: you cant see it, but with the above example the space after "stel" is the fifth character.

This is my output with a short name:

Orginal string size >>9 size of name>>5 Position>> 4
Orginal string >>Don 00:09 Substring >>00:09

with the shorter name i get my timestamp perfectly.

How can make this works consistent.
I did not added the rest of my code because that part works. it is basically only the substring part that does not work consistent.

How can i fix this?

Answer Source

You're not calculating test correctly. It should just be 1 more than the size of the name, not the size of HighScoreInfo1 minus that (that's the length of the timestamp, which you know is 5). You only need to add 1, not 2, because positions are zero-based.

int test = previous_name.size() + 1;


It only works with the shorter name by coincidence, because the name happens to be 3 characters long.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download