簡體   English   中英

有沒有一種方法可以指定使用printf()打印出一個字符串中的多少個字符?

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

有沒有一種方法可以指定要輸出的字符串中的多少個字符(類似於int的小數位)?

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

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

基本方法是:

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規范定義了這些機制。

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

%8s將指定至少8個字符的寬度。 您想在8處截斷,因此請使用%.8s。

如果您想始終打印8個字符,可以使用%8.8s

使用printf您可以做

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

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

或者,效率較低:

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

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

印刷品:

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

在C ++中,這很容易。

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

編輯:將它與字符串迭代器一起使用也更安全,因此您不會跑到盡頭。 我不確定printf和string太短會發生什么,但是我猜這可能更安全。

打印前四個字符:

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

有關更多信息,請參見此鏈接 (請檢查.precision-section)

printf(.....“%。8s”)

在C ++中,我是這樣進行的:

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

請注意,這是不安全的,因為在傳遞第二個參數時,我可能會超出字符串的大小並產生內存訪問沖突。 您必須實施自己的檢查來避免這種情況。

暫無
暫無

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

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