gpt4 book ai didi

c++ - 有没有办法指定使用 printf() 打印出字符串的多少个字符?

转载 作者:行者123 更新时间:2023-11-30 16:12:45 26 4
gpt4 key购买 nike

有没有办法指定要打印的字符串的字符数(类似于 int 中的小数位)?

printf ("Here are the first 8 chars: %s\n", "A string that is more than 8 chars");

希望打印:这是前 8 个字符:一个字符串

最佳答案

基本方法是:

printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");

另一种通常更有用的方法是:

printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");

在这里,您将长度指定为 printf() 的 int 参数,它将格式中的“*”视为从参数获取长度的请求。

您还可以使用符号:

printf ("Here are the first 8 chars: %*.*s\n",
8, 8, "A string that is more than 8 chars");

这也类似于“%8.8s”表示法,但再次允许您在运行时指定最小和最大长度 - 在以下场景中更现实:

printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);

printf() 的 POSIX 规范定义了这些机制。

关于c++ - 有没有办法指定使用 printf() 打印出字符串的多少个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com