By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,795 Members | 1,761 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,795 IT Pros & Developers. It's quick & easy.

std::string to char[] with a twist

P: n/a
Hello,

I need your expertise to perform a conversion.

I need to convert a std::string to a char[32]. However, in the
conversion, I need to get rid of the '/0' character. The initial string
represents a 256 bit (32 byte) numeric value. Therefore, the resulting
char[32] should not contain '/0'.

If you have any suggestions, please let me know.

Aug 8 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a

ruffiano napísal(a):
Hello,

I need your expertise to perform a conversion.

I need to convert a std::string to a char[32]. However, in the
conversion, I need to get rid of the '/0' character. The initial string
represents a 256 bit (32 byte) numeric value. Therefore, the resulting
char[32] should not contain '/0'.

If you have any suggestions, please let me know.
How about:

std::string src;
char dst[32];
memcpy(dst, src.data(), 32);

Plus some additional bounds checking, etc.

Aug 8 '06 #2

P: n/a
ruffiano posted:
Hello,

I need your expertise to perform a conversion.

I need to convert a std::string to a char[32]. However, in the
conversion, I need to get rid of the '/0' character. The initial string
represents a 256 bit (32 byte) numeric value. Therefore, the resulting
char[32] should not contain '/0'.

There's no need to get rid of the null terminator; just pretend it isn't
there.

If you have any suggestions, please let me know.

#include <cassert>
#include <string>
#include <iostream>

using std::string;
using std::cout;

unsigned const magic = 32;

char const inline (&Func(string const &str))[magic]
{
char const *const p = str.c_str();

assert(strlen(p) >= magic);

return reinterpret_cast<char const (&)[magic]>(*p);
}

int main()
{
string str("abcdefghijklmnopqrstuvwxyzabcdef");

char const (&arr)[magic] = Func(str);

char const *p = arr;
char const *const p_over = arr + magic;

do
{
cout << *p++;
} while (p != p_over);
}

--

Frederick Gotham
Aug 8 '06 #3

P: n/a

ruffiano wrote:
Hello,

I need your expertise to perform a conversion.

I need to convert a std::string to a char[32]. However, in the
conversion, I need to get rid of the '/0' character. The initial string
represents a 256 bit (32 byte) numeric value. Therefore, the resulting
char[32] should not contain '/0'.

If you have any suggestions, please let me know.
Why do you think you need to do this? You might not.

Aug 8 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.