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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2239519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:39:52  来源:igfitidea点击:

Is there a way to specify how many characters of a string to print out using printf()?

c++cprintf

提问by T.T.T.

Is there a way to specify how many characters of a string to print out (similar to decimal places in ints)?

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

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

Would like it to print: Here are the first 8 chars: A string

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

回答by Jonathan Leffler

The basic way is:

基本方法是:

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

The other, often more useful, way is:

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

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

Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument.

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

You can also use the notation:

您还可以使用符号:

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

This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like:

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

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

The POSIX specification for printf()defines these mechanisms.

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

回答by developmentalinsanity

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

%8s would specify a minimum width of 8 characters. You want to truncate at 8, so use %.8s.

%8s 将指定最小宽度为 8 个字符。你想在 8 处截断,所以使用 %.8s。

If you want to always print exactly 8 characters you could use %8.8s

如果你想总是打印 8 个字符,你可以使用 %8.8s

回答by hlovdal

In addition to specify a fixed amount of characters, you can also use *which means that printf takes the number of characters from an argument:

除了指定固定数量的字符外,您还可以使用*这意味着 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;
}

Prints:

印刷:

message: 'Hel'
message: 'Hel'
message: 'Hello'

回答by Peter Alexander

Using printfyou can do

使用printf你可以做

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

If you're using C++, you can achieve the same result using the STL:

如果您使用的是 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;

Or, less efficiently:

或者,效率较低:

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

回答by Anssi

Print first four characters:

打印前四个字符:

printf("%.4s\n", "A string that is more than 8 chars");

printf("%.4s\n", "A string that is more than 8 chars");

See this linkfor more information (check .precision -section)

有关更多信息,请参阅此链接(检查 .precision -section)

回答by Chris H

In C++ it is easy.

在 C++ 中,这很容易。

std::copy(someStr.c_str(), someStr.c_str()+n, std::ostream_iterator<char>(std::cout, ""));

EDIT: It is also safer to use this with string iterators, so you don't run off the end. I'm not sure what happens with printf and string that are too short, but I'm guess this may be safer.

编辑:将它与字符串迭代器一起使用也更安全,所以你不会跑到最后。我不确定太短的 printf 和 string 会发生什么,但我猜这可能更安全。

回答by pm100

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

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

回答by rodolk

In C++, I do it in this way:

在 C++ 中,我是这样做的:

char *buffer = "My house is nice";
string showMsgStr(buffer, buffer + 5);
std::cout << showMsgStr << std::endl;

Please note this is not safe because when passing the second argument I can go beyond the size of the string and generate a memory access violation. You have to implement your own check for avoiding this.

请注意这并不安全,因为在传递第二个参数时,我可能会超出字符串的大小并生成内存访问冲突。您必须实施自己的检查以避免这种情况。