AdyAdy
AdyAdy

Reputation: 1038

C++ - Specify maximum character for std::cout when printing char*

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.)

Upvotes: 8

Views: 8012

Answers (3)

Antua
Antua

Reputation: 185

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");

Upvotes: 0

Joseph Franciscus
Joseph Franciscus

Reputation: 371

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).

Upvotes: 7

Benjamin Barrois
Benjamin Barrois

Reputation: 2686

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.

Upvotes: -3

Related Questions