D-Antonio D-Antonio - 4 months ago 12
C++ Question

Using Substring properly C++,

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
int test = HighScoreInfo1.size() - (previous_name.size()+2 );

This calculates the length of the time (which is always 5).

TimeToBeat = HighScoreInfo1.substr(test, 5);

This gets the characters 5-10. Always. Regardless of the length of the string. Perhaps you meant to do this, which reads the last five bytes?

TimeToBeat = HighScoreInfo1.substr(HighScoreInfo1.size()-5);
Comments