C++ - 在打印char*时指定std :: cout的最大字符数

Ady*_*Ady 4 c++ std c++17

假设我有一个const char*,我想用std :: cout打印,但我只想要打印前X个字符.有没有办法告诉std :: cout?(不在字符串中插入终止空值或制作临时副本.)

Jos*_*cus 5

C++ 17介绍 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; 
}
Run Code Online (Sandbox Code Playgroud)

我没有尝试编译上面的代码.string_view基本上是一个字符串,除了它不"拥有"它的内容(使用后不会删除内部指针).