-5

I have unsigned char array. I want to print all array value by using cout. How can I do that?

rtc::ZeroOnFreeBuffer<unsigned char> charArray(key_len * 2 + salt_len * 2);

cout<< charArray; --> ?
propoLis
  • 1,229
  • 1
  • 14
  • 48

2 Answers2

2
for (auto&& c : charArray){
    cout << c;
}

is probably the simplest way, assuming you want the actual characters rather than the numbers (if you want numbers then replace auto&& with int), and your container is iterable.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 2
    If the integer values are preferred, then `cout << static_cast(c) << ' ';` – Eljay Sep 18 '18 at 13:05
  • 2
    @Eljay: I kinda prefer my way ;-) – Bathsheba Sep 18 '18 at 13:08
  • On second read, yes, I agree with you use of `int` rather than `auto&&` if integer value is being emphasized rather than character association. Your code is more succinct. Both are self-documenting code. I'd change my code to your solution in a code review. – Eljay Sep 18 '18 at 13:18
  • 1
    Question @Bathsheba: why `auto&&` instead of `const auto&`? – rsjaffe Sep 18 '18 at 13:57
  • @rsjaffe: It's a bit patronising I know but I like to bury these things into my answers. See https://stackoverflow.com/questions/26991393/what-does-auto-e-do-in-range-based-for-loops. – Bathsheba Sep 18 '18 at 13:58
  • I'm not sure the questioner uses a standard container--looks like a buffer to me, so without knowing the derivation of ZeroOnFreeBuffer, the range-for loop may not work. – rsjaffe Sep 18 '18 at 14:03
  • @rsjaffe: Indeed, I disclaim that with the informal "and your container is iterable". – Bathsheba Sep 18 '18 at 14:03
  • please delete your answer – propoLis Jun 02 '21 at 16:38
  • @propoLis Why? If you want to disassociate your account with this question (due to downvoting?) then ask the moderators. They do that from time to time. The mods might delete the thread altogether; an action I would support. – Bathsheba Jun 02 '21 at 17:52
1

Assuming you're using the ZeroOnFreeBuffer from WebRTC, you can use a for loop, and obtain the current size of the buffer:

size_t bufSize = charArray.size()
for (int i = 0; i < bufSize; i++){
    cout << charArray[i];
}

In any case, how you access the data and iterate over it depends upon the nature of ZeroOnFreeBuffer. Look at the documentation for that object, and it will give you methods to access the data, find the size of the buffer, and perhaps even how to obtain iterators for such things as range-for loops.

rsjaffe
  • 5,600
  • 7
  • 27
  • 39