8

Let's say I have a const char* that I want to print with std::cout but I only want the first X characters to be printed. Is there a way to tell that to std::cout? (Without inserting a terminating-null into the string or making a temporary copy.)

Tim Randall
  • 4,040
  • 1
  • 17
  • 39
AdyAdy
  • 988
  • 6
  • 19

3 Answers3

7

C++ 17 introduces string_view

#include <string_view>
#include <iostream> 

char message[] = { "my long char message" };
int length = some_number; 

int main() { 
      string_view str(message); 
      std::cout << str.substr(0, length) << std::endl; 
}

I have not tried to compile the above code. string_view is basically a string except that it does not 'own' its contents (will not delete the internal pointer after use).

BluesSolo
  • 608
  • 9
  • 28
  • 1
    Or direct: `std::cout< – MSalters Aug 03 '18 at 14:28
  • To add some color to this: `string_view` is a way to treat any existing memory as if it were a `string` (whether or not that memory actually contains string data is irrelevant; you can get a `u32string_view` into an array of 32-bit values to manipulate them as if they were characters, if you'd like). This is, however, something to be cautious of when using `string_view`: if the memory it's looking at goes out of scope or otherwise gets deallocated, things are going to go south fast. That's not likely to matter in this usage, but it's worth bearing in mind. – bionicOnion Aug 03 '18 at 14:30
0

I don't know of such functionality for std::cout, but you may want to see at printf(), see an example here.

For example:

printf ("The 8 chars: %*.*s\n", min, max, "String that you want to limit");
Antua
  • 185
  • 9
  • You really should so how to use it in this answer to make it a good one. having the information behind a link makes this answer not as useful and if the link ever breaks then they are SOL – NathanOliver Aug 03 '18 at 13:39
-3

If you want to be compatible with any standard, you can make a simple macro:

#define CROPPED_STRING(str, len) ( (str.size() <= len) ? (str) : (str.substr(0, len)) )

and use it this way:

std::cout << CROPPED_STRING("Hello World", 7) << std::cout;

which displays Hello W.

Optionally you can add control on len to be sure it is > 0.

Benjamin Barrois
  • 2,566
  • 13
  • 30