Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ substring returning wrong results

Tags:

c++

substring

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?

like image 315
jviotti Avatar asked Oct 10 '12 19:10

jviotti


2 Answers

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";
like image 185
John Dibling Avatar answered Oct 10 '22 05:10

John Dibling


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.

like image 37
William Avatar answered Oct 10 '22 03:10

William