Hello, this is one examples that I always panic with C printf format specifier.
1) I did read the manpage with
man 3 printf
...... One can also specify explicitly which argument is taken, at each place where an argument is required, by writing
"%m$" instead of '%' and "*m$" instead of '*', where the decimal integer m denotes the position in the argument list of the desired
argument, indexed starting from 1. Thus,
printf("%*d", width, num);
and
printf("%2$*1$d", width, num);
are equivalent. The second style allows repeated references to the same argument.
1) Can you please explain this example on width and num for me.
2) To have further understanding I used following code from "A book on C by Al Kelley/Ira Pohl, page 503" to test,
#include <stdio.h>
int main()
{
int i;
char c;
char string[15];
printf("Please input a line:\n");
scanf("%d , %*s %% %c %5s %s", &i, &c, string, &string[5]);
//input: 45 , ignore_this, % C read_in_this**
printf("%d , %*s %% %c %5s %c", &i, &c, string, &string[5]);
return 0;
}
but I met two problems. 1) A bunch of warnings as I mentioned in my last threads:
pg503.c: In function �main�:
pg503.c:13:2: warning: format �%d� expects argument of type �int�, but argument 2 has type �int *� [-Wformat]
pg503.c:13:2: warning: field width specifier �*� expects argument of type �int�, but argument 3 has type �char *� [-Wformat]
pg503.c:13:2: warning: format �%c� expects argument of type �int�, but argument 5 has type �char *� [-Wformat]
pg503.c:13:2: warning: format �%s� expects a matching �char *� argument [-Wformat]
pg503.c:13:2: warning: format �%c� expects a matching �int� argument [-Wformat]
2) when I tried:
./a.out
Please input a line:
45 , ignore_this, % C read_in_this**
Note: Spaces after 45, two asterisks were put at the end on purpose, and I was expecting to see:
45
,
read_
in_this**
The program went infinite, nothing was printed. Thank you!