Programing

printf ()를 사용하여 인쇄 할 문자열의 문자 수를 지정하는 방법이 있습니까?

crosscheck 2020. 8. 5. 07:49
반응형

printf ()를 사용하여 인쇄 할 문자열의 문자 수를 지정하는 방법이 있습니까?


인쇄 할 문자열의 문자 수를 지정하는 방법이 int있습니까 (s의 소수점 이하 자릿수와 유사 )?

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

POSIX 사양 printf()은 이러한 메커니즘 정의합니다.


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'

처음 네 글자를 인쇄하십시오.

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

자세한 내용은 이 링크 를 참조하십시오 (.precision -section 확인).


C ++에서는 쉽습니다.

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

편집 : 문자열 반복자와 함께 사용하는 것이 더 안전하므로 끝까지 도망 가지 않습니다. printf와 string이 너무 짧은 결과가 확실하지 않지만 이것이 더 안전하다고 생각합니다.


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


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.

참고URL : https://stackoverflow.com/questions/2239519/is-there-a-way-to-specify-how-many-characters-of-a-string-to-print-out-using-pri

반응형