tags:

views:

202

answers:

1

Hi, having something like this:

void print_signs()
{
const char* chars[] = {"abcdefghijklmnopqrstuvwxyz0123456789"};
std::copy(chars,chars + 1,std::ostream_iterator<const char*>(cout));
cout << hex; //trying to change the way output works for next line
std::copy(chars,chars + 1,std::ostream_iterator<const char*>(cout));
}

is there a way to have cout print them in hex format (using STL components only)? Thank you.

+1  A: 
void print_signs()
{
    const std::string chars("abcdefghijklmnopqrstuvwxyz0123456789");
    std::cout << std::hex;
    std::copy(chars.begin(), chars.end(), std::ostream_iterator<int>(std::cout));
}

And If you wan't to preserve the exact typing of the original:

void print_signs()
{
    const char* chars[] = {"abcdefghijklmnopqrstuvwxyz0123456789"};
    const size_t charCount = strlen(chars[0]);
    std::cout << std::hex;
    std::copy(chars[0], chars[0] + charCount, std::ostream_iterator<int>(std::cout));
}

If you absolutely don't want to use strlen I you could use:

const size_t charCount = std::string(chars[0]).length();

but this is not as efficient as std::string(...) will need to allocate memory from the heap.

/A.B.

Andreas Brinck
I guess the author ask using STL components only
Priyank Bolia
Fixed, can you upvote? ;)
Andreas Brinck
I'm sorry but before answering to my question did you take a look at the last line in my post?"is there a way to have cout print them in hex format (using STL components only)?" - stress on STL only - thats the first objection I have to your "answer".
There is nothing we can do
Secondly, did you actually check if your loop works? Did you know that operator sizeof will return size of an object in this case const char* which is 4? Did you know that you should really use '\n' instead of std::endl and last but not least did you know that comparing signed int (i) with unsigned int (value returned by sizeof) is just very poor coding style. Did you know all this things? Another example on how many mistakes can one make in two lines of basic code. Please don't answer to my questions any more.
There is nothing we can do
That's pretty rude.
Andreas Brinck
Please point out fragment in my comment which is rude according to you.
There is nothing we can do
I thought your comment was a bit condescending, if my (edited) answer is to your satisfaction you should accept it.
Andreas Brinck
I would accept your answer only you've change my example (in your is string in my was const char*) which is not what I was asking for.
There is nothing we can do
Ok, I've changed the code snippet to use 'const char*' instead.
Andreas Brinck
Thanks, it works as it supposed to.
There is nothing we can do