What does this statement mean ? printf(“[%.*s] ”, (int) lengths[i],

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!