c - %.*s 在这个程序中有什么用

标签 c

<分区>

我有以下程序:

#include <stdio.h>
#include <stdlib.h>

int main()

{
    static char string[12];
    int length,c,d;
    printf("Enter a string :");
    gets(string);
    length=strlen(string);
    printf("\nLength of the string is %d",length);
    for(c=0;c<=length-2;c++)
    {
        d=c+1;
        printf("\t%.*s\n",d,string);
    }
    for(c=length;c>=0;c--)
    {
        d=c+1;
        printf("\t%.*s\n",d,string);
    }
} 

我对 printf 语句中 %.*s 的用法感到非常困惑。我知道 %s 用于显示字符串,但我对这个程序中 s 之前的 .* 的用法感到困惑。此外,在 printf 语句的引号内只提到了一种数据类型 (%s),但在 printf 语句中提到了两个变量。

最佳答案

它是一个精度组件,指定字符串转换的最大字节数。 Asterisk (*),使用整数参数,指定要使用的值(用于精度)。

例如,如下代码:

#include <stdio.h>

int main(int argv, char **argc)
{
    char *s = "hello, world";
    printf("%.*s\n", 4, s);
    return 0;
}

给出输出:

hell

关于c - %.*s 在这个程序中有什么用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18169361/

相关文章:

写入内存时 scanf C 中的 char[] 与 char*

c - 同时使用信号量和互斥体是一个好方法吗?

c - 访问类型的 Ada 数组

c - 如何在 Linux 中将套接字链接到 PID?

c - 对于 <stdbool.h> 中的 bool 类型,eclipse cdt 格式化程序的行为不正确

c - 解引用指针构造的地址

c - tcl 多线程就像在 c 中一样,很难用过程执行线程

c - 学习C而无需编译为* .exe?

c - 为什么未命名的信号量在共享内存中使用时不会改变?

c++ - 如何在 C++ 中将单个字节写入文件