jviotti
jviotti

Reputation: 18939

C++ substring returning wrong results

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?

Upvotes: 7

Views: 5150

Answers (3)

Adrian Herea
Adrian Herea

Reputation: 658

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.

Upvotes: -1

William
William

Reputation: 830

Try this:

std::cout << "** Date: " << date << "\n";
std::cout << "Year: " << date.substr(0,4) << "\n";
std::cout << "Month: " << date.substr(4,2) << "\n";
std::cout << "Day: " << date.substr(6,2) << "\n";

I believe substr takes start and length as arguments.

Upvotes: 3

John Dibling
John Dibling

Reputation: 101494

std::cout << "Month: " << date.substr(4,6) << "\n";

The second argument is wrong. You are specifying, "Give me as substring of 6 characters, starting at position 4."

You probably want:

std::cout << "Month: " << date.substr(4,2) << "\n";

Upvotes: 21

Related Questions