See CppReference
operator []
No bounds checking is performed. If
pos > size()
, the behavior is undefined.
When you define string r
, its size()
is zero, so all your character assignments are undefined behaviors. You may want to resize it first:
r.resize(9);
Or alternatively, append the characters one-by-one:
r = "";
r.push_back(hh/10+'0');
r.push_back(hh%10+'0');
r.push_back(':');
r.push_back(mm/10+'0');
r.push_back(mm%10+'0');
r.push_back(':');
r.push_back(ss/10+'0');
r.push_back(ss%10+'0');
// This isn't necessary
// r.push_back('\0');
Using operator+=
makes your code look more natural:
r = "";
r += hh/10+'0';
r += hh%10+'0';
r += ':';
r += mm/10+'0';
r += mm%10+'0';
r += ':';
r += ss/10+'0';
r += ss%10+'0';
// This isn't necessary
// r += '\0';
Note you don’t need the terminating zero because std::basic_string
isn’t null-terminated (it’s not C-style string).
5
solved C++ : Why my string is not getting printed?