What is the modern way to do this? Headers like <cstring>
are deprecated and "C-like" functions are banned by some coding styles. I have three approaches of doing the same thing. Which one would be most idiomatic of modern C++?
1. Use iterators and include the null terminator
{
std::string test{"hello, world!"};
char* output = new char[test.size() + 1];
std::copy(test.begin(), test.end(),
output);
output[test.size() + 1] = '\0';
std::cout << output;
delete output;
}
2. Use c_str()
which includes the null terminator
{
std::string test{"hello, world!"};
char* output = new char[test.size() + 1];
std::copy(test.c_str(), test.c_str() + std::strlen(test.c_str()),
output);
std::cout << output;
delete output;
}
3. Use std::strcpy
{
std::string test{"hello, world!"};
char* output = new char[test.size() + 1];
std::strcpy(output, test.c_str());
std::cout << output;
delete output;
}
I don't want to look like a noob to an interviewer who say "Oh you use strcpy, you must be a C programmer".