Re: copying contents from a char array to std::string obj
* Ramesh:
Hi.
Assuming I have a code snippet like below:
#include <iostream>
using namespace std;
char Mac[6] = { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5 };
std::string csMac;
1. Whats the best way to do a deep copy from the c-style char array to
the c++ string object.
"best" is not meaningful without some criteria.
And as Christian Hackl remarked else-thread you're probably better off using
some other container type, not a string.
One way to initialize a std::string from the data is
#include <iostream>
#include <string>
template< typename T, size_t N >
T const* begin( T const (&a)[N] ) { return a; }
template< typename T, size_t N >
T const* end( T const (&a)[N] ) { return a + N; }
int main()
{
using namespace std;
static char const macValues[6] = { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5 };
std::string const mac( begin(macValues), end(macValues) );
for( size_t i = 0; i < mac.length(); ++i )
{
cout << (int) mac[i] << ' ';
}
cout << endl;
}
I know the other way around to assign to the string object (to use a
c_str() on the string).
That's not "the other way", that's a conversion to pointer to zero-terminated
string. You don't have a zero-terminated string in the first place.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?