programing

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

itsource 2022. 7. 29. 23:25
반응형

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

출력할 문자열의 문자 수를 지정하는 방법이 있습니까(의 소수 자릿수와 유사).ints)?

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는 인수에서 문자 수를 가져옵니다.

#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 ("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;

처음 4글자 인쇄:

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와 문자열이 너무 짧으면 어떻게 될지 모르겠지만, 이게 더 안전할 것 같아요.

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

C++에서는 다음과 같이 합니다.

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

두 번째 인수를 전달하면 문자열 크기를 초과하여 메모리 액세스 위반을 생성할 수 있으므로 안전하지 않습니다.이를 피하기 위해서는 자신의 체크를 실시해야 합니다.

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

반응형