1

For example, I have a string and I want to write a function that will printf a part of it to the screen with the length printed is not initialized but defined latter wether by function or input data

normally

char str[70]="my name is Jack";
printf("%.4s", str[11])

the result will be "Jack"

However now the length to be written to stdout now is now specified

char str[70]="my name is Jack";
int x;
scanf("%d",&x);

now I the length will be define later so How to use it with printf I now just using this method

char str[70]="my name is Jack";
int x, i;
scanf("%d",&x);
for(i=0, i<x, i++){
    printf("%c", str[11+i]);

this will work but I want to know is there any way to printf without using loop. I tried

printf("%.xc", str[11+i]);

but the result is incorrect, so this is not the way.

aukxn
  • 231
  • 1
  • 4
  • 8

1 Answers1

3

Use * in the printf conversion specifier

char data[] = "The name is Jack Monroe";
int length = 4;
int start = 12;
printf("%.*s", length, data + start); // Jack
pmg
  • 106,608
  • 13
  • 126
  • 198
  • Hi, can you give me some reference of * conversion specifer, I use google but the result doesn't satisfy me – aukxn Mar 26 '15 at 16:51
  • http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html "An optional precision that gives ... the maximum number of bytes to be printed from a string in the s conversion specifier." – pmg Mar 26 '15 at 16:54
  • Also http://port70.net/~nsz/c/c11/n1570.html#7.21.6.1 for the same text – pmg Mar 26 '15 at 16:56