有没有办法使用printf()指定要打印的字符串的字符数?

T.T*_*.T. 109 c c++ printf

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

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

想要打印: Here are the first 8 chars: A string

Jon*_*ler 206

基本方法是:

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

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

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

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

您也可以使用表示法:

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

这也类似于"%8.8s"符号,但同样允许您在运行时指定最小和最大长度 - 在以下情况中更实际:

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

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

  • 输出将为空白填充(在左侧除非您添加`-`)以使其达到指定的完整长度. (4认同)
  • 到最后一个例子:如果复制的字符串比minlen短,该怎么办? (2认同)
  • 如果想在“C”上下文中使用“std::string_view”而不升级到“std::string”,这是一个很棒的技巧。 (2认同)

dev*_*ity 12

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

%8s将指定最小宽度为8个字符.您希望截断为8,因此请使用%.8s.

如果您想要始终打印8个字符,则可以使用%8.8s


Pet*_*der 11

printf你可以做到

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

如果您使用的是C++,则可以使用STL获得相同的结果:

using namespace std; // for clarity
string s("A string that is more than 8 chars");
cout << "Here are the first 8 chars: ";
copy(s.begin(), s.begin() + 8, ostream_iterator<char>(cout));
cout << endl;
Run Code Online (Sandbox Code Playgroud)

或者,效率较低:

cout << "Here are the first 8 chars: " <<
        string(s.begin(), s.begin() + 8) << endl;
Run Code Online (Sandbox Code Playgroud)

  • 注意:**不要**使用`ostream_iterator&lt;char&gt;(cout)`!相反,使用`ostreambuf_iterator&lt;char&gt;(cout)`!性能上的差异应该是相当大的。 (2认同)

hlo*_*dal 10

除了指定固定数量的字符外,您还可以使用*这意味着printf从参数中获取字符数:

#include <stdio.h>

int main(int argc, char *argv[])
{
        const char hello[] = "Hello world";
        printf("message: '%.3s'\n", hello);
        printf("message: '%.*s'\n", 3, hello);
        printf("message: '%.*s'\n", 5, hello);
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

打印:

message: 'Hel'
message: 'Hel'
message: 'Hello'
Run Code Online (Sandbox Code Playgroud)


pm1*_*100 5

printf(....."%.8s")