While I was using c_str() to transform std::string into C-style string, I didn't see the last character overridden by the null-termination which c_str() is supposed to add in this program:
#include<iostream> #include<string> #include<cstring> using namespace std; int main() { string s = "helloworld"; char c[10]; strcpy(c, s.c_str()); cout << c << endl; return 0; } What I am asking is why d is being printed (added to c) as I was expecting null-termination to be there. What am I missing here?
strcpyputs the terminator after the the string it writes. If the buffer is too small, that's your problem.