I have this string:
std::string date = "20121020";
I'm doing:
std::cout << "** Date: " << date << "\n";
std::cout << "Year: " << date.substr(0,4) << "\n";
std::cout << "Month: " << date.substr(4,6) << "\n";
std::cout << "Day: " << date.substr(6,8) << "\n";
But im getting:
** Date: 20121020
Year: 2012
Month: 1020
Day: 20
Notice that month should be 10
, not 1020
. Positions are correct, tried everything, that is it failing?
The second argument is wrong. You are specifying, "Give me as substring of 6 characters, starting at position 4."
You probably want:
http://www.cplusplus.com/reference/string/string/substr/
string substr ( size_t pos = 0, size_t n = npos ) const;
pos Position of a character in the current string object to be used as starting character for the substring. If the position passed is past the end of the string, an out_of_range exception is thrown.
n Length of the substring. If this value would make the substring to span past the end of the current string content, only those characters until the end of the string are used. npos is a static member constant value with the greatest possible value for an element of type size_t, therefore, when this value is used, all the characters between pos and the end of the string are used as the initialization substring.
So your mistake in code is that you have expected that the second parameter to be the position of the last char instead of the length of the substring.
Try this:
I believe substr takes start and length as arguments.