printf() を使用して文字列の何文字を出力するかを指定する方法はありますか? 質問する

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

ベストアンサー1

基本的な方法は次のとおりです。

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() は、フォーマット内の '*' を引数から長さを取得する要求として扱います。

次の表記法も使用できます。

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()これらのメカニズムを定義します。

おすすめ記事