2

I have a character range with pointers (pBegin and pEnd). I think of it as a string, but it is not \0 terminated. How can I print it to std::cout effectively?

  • Without creating a copy, like with std::string
  • Without a loop that prints each character

Do we have good solution? If not, what is the smoothest workaround?

Yu Hao
  • 111,229
  • 40
  • 211
  • 267
Notinlist
  • 14,748
  • 9
  • 51
  • 92
  • What's wrong with the copy from `std::string( pBegin, pEnd )`? That's the natural way of doing it (and the copy won't be noticeable compared to the time taken by the actual output). – James Kanze Jul 12 '13 at 11:27
  • The answer is very useful for me. Maybe I transformed the question too much from the original problem and should have asked about `std::ostream`, which can be `std::stringstream`. where the difference may count. – Notinlist Jul 12 '13 at 11:37

2 Answers2

6

You can use ostream::write, which takes pointer and length arguments:

std::cout.write(pBegin, pEnd - pBegin);
Magnus Hoff
  • 20,105
  • 8
  • 58
  • 81
0

Since C++17 you can use std::string_view, which was created for sharing part of std::string without copying

std::cout << std::string_view(pBegin, pEnd - pBegin);

pEnd must point to one pass the last character to print, like how iterators in C++ work, instead of the last character to print

In older C++ standards boost::string_ref is an alternative. Newer boost versions also have boost::string_view with the same semantics as std::string_view. See Differences between boost::string_ref and boost::string_view

If you use Qt then there's also QStringView and QStringRef although unfortunately they're used for viewing QString which stores data in UTF-16 instead of UTF-8 or a byte-oriented encoding

However if you need to process the string by some functions that require null-terminated string without any external libraries then there's a simple solution

char tmpEnd = *pEnd;  // backup the after-end character
*pEnd = '\0';
std::cout << pBegin;  // use it as normal C-style string, like dosomething(pBegin);
*pEnd = tmpEnd;       // restore the char

In this case make sure that pEnd still points to an element inside the original array and not one past the end of it

phuclv
  • 27,258
  • 11
  • 104
  • 360