Is there a more C++y way to do that?
As far as the construction of the std::string
is concerned, not really. Though, at the very least, since you already know the max length of the char[]
, you can use the std::string(const char*, size_type)
constructor instead of the std::string(InputIt, InputIt)
constructor, thus the constructor can avoid having to calculate the length:
std::string(txt_msg, ::strnlen(txt_msg, sizeof(txt_msg));
Since strnlen()
is a non-standard POSIX extension, it would not be hard to write a manual implementation, if needed:
#include <algorithm>
size_t strnlen(const char *s, size_t maxlen)
{
const char *s_end = s + maxlen;
const char *found = std::find(s, s_end, '\0');
return (found != s_end) ? size_t(found - s) : maxlen;
}
That being said, a C++ solution to your problem would be to wrap the std::string
construction in a helper template function, eg:
template<size_t N>
std::string to_string(const char (&arr)[N])
{
return std::string(arr, strnlen(arr, N));
}
And then you can do this when needed:
char txt_msg[80];
...
std::string s = to_string(txt_msg);
Rather than doing this:
char txt_msg[80];
...
std::string s = std::string(txt_msg, txt_msg + strnlen(txt_msg, sizeof(txt_msg)));
//or
std::string s = std::string(txt_msg, strnlen(txt_msg, sizeof(txt_msg)));