簡體   English   中英

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

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

假設我有一個const char *,我想用std :: cout打印,但我只想要打印前X個字符。 有沒有辦法告訴std :: cout? (不在字符串中插入終止空值或制作臨時副本。)

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; 
}

我沒有嘗試編譯上面的代碼。 string_view基本上是一個字符串,除了它不“擁有”它的內容(使用后不會刪除內部指針)。

我不知道std::cout的這種功能,但你可能想看看printf() ,請看這里的一個例子。

例如:

printf ("The 8 chars: %*.*s\n", min, max, "String that you want to limit");

如果您想與任何標准兼容,您可以制作一個簡單的宏:

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

並以這種方式使用它:

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

顯示Hello W

(可選)您可以在len上添加控件以確保它> 0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM