可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I was reading this page http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html there is one line
printf("[%.*s] ", (int) lengths[i], row[i] ? row[i] : "NULL");
from code
MYSQL_ROW row; unsigned int num_fields; unsigned int i; num_fields = mysql_num_fields(result); while ((row = mysql_fetch_row(result))) { unsigned long *lengths; lengths = mysql_fetch_lengths(result); for(i = 0; i < num_fields; i++) { printf("[%.*s] ", (int) lengths[i], row[i] ? row[i] : "NULL"); } printf("\n");
}
what does [%.*s]
mean in that code ?
回答1:
[%.*s]
is a printf
format string meaning:
- the first argument should be an integer (specifying maximum length of a string to print).
- the second argument should be the string itself.
- the
[
and ]
(and trailing space) are transferred as-is.
Normally, you would see something like .7s
which means a 7-character string. The use of *
for the length means to take it from the argument given.
So what that entire line does is to print a string , the length of which is found in lengths[i]
, and the value of which is row[i]
(unless row[i]
is NULL, in which case it uses the literal string "NULL"
).
回答2:
%.*s
is an output format string.
http://www.cplusplus.com/reference/clibrary/cstdio/printf/
printf("[%.*s] ", (int) lengths[i], row[i] ? row[i] : "NULL");
Specifically in this case it means to print the the second argument (contents of row[i]
or 'NULL' if contents of row[i]
evaluate to false) with a maximum of lengths[i]
characters. The square brackets are not part of the formatting, they get printed themselves
回答3:
the [%.*s]
part is a format string for printf.
it specifies that printf()
should output a string (row[i]
) but should limit the output to the length specified by a parameter (length[i]
). the output string is enclosed inside square brackets.
see the printf()
documentation for more information on format strings.