17
int x;
printf("hello %n World\n", &x);
printf("%d\n", x);
4

8 回答 8

15

它对 不太有用printf(),但对 非常有用sscanf(),尤其是当您在多次迭代中解析字符串时。 fscanf()scanf()根据读取的输入量自动推进其内部指针,但sscanf()不会。例如:

char stringToParse[256];
...
char *curPosInString = stringToParse;  // start parsing at the beginning
int bytesRead;
while(needsParsing())
{
    sscanf(curPosInString, "(format string)%n", ..., &bytesRead);  // check the return value here
    curPosInString += bytesRead;  // Advance read pointer
    ...
}
于 2008-12-09T18:02:57.117 回答
5

它可以用来做恶事

于 2008-12-09T18:08:57.307 回答
4

看你说的实用是什么意思。总是有其他方法可以完成它(例如,使用 s[n]printf 打印到字符串缓冲区并计算长度)。

然而

int len;
char *thing = "label of unknown length";
char *value = "value value value"
char *value2="second line of value";
printf ("%s other stuff: %n", thing, &len);
printf ("%s\n%*s, value, len, value2);

应该产生

label of unknown length other stuff: value value value
                                     second line of value

(虽然未经测试,但我不在 C 编译器附近)

作为一种对齐方式,这几乎是实用的,但我不想在代码中看到它。有更好的方法来做到这一点。

于 2008-12-09T18:02:43.043 回答
3

这是相当深奥的。如果您稍后需要在生成的字符串中替换占位符,您可能需要记住字符串中间的索引,这样您就不必保存原始 printf 参数或解析字符串。

于 2008-12-09T17:53:55.340 回答
1

它可能被用作获取各种子字符串长度的快速方法。

于 2008-12-09T17:57:16.237 回答
1
#include <stdio.h>
int main(int argc, char* argv[])
{
    int col10 = (10 - 1);
    int col25 = (25 - 1);

    int pos1 = 0;
    int pos2 = 0;

    printf("    5    10   15   20   25   30\n");

    printf("%s%n%*s%n%*s\n",                     "fried", 
                            &pos1, col10 - pos1, "green",   
                            &pos2, col25 - pos2, "tomatos");


    printf("    ^    ^    ^    ^    ^    ^\n");

    printf("%d %d\n", pos1, pos2);
    printf("%d %d\n", col10 - pos1, col25 - pos2);

    return 0;
}

我肯定在这里遗漏了一些东西。西红柿太靠右了。

于 2008-12-09T19:19:49.783 回答
0

这是来自 VS2005 CRT 代码的内容:

/* if %n is disabled, we skip an arg and print 'n' */
if ( !_get_printf_count_output() )
{
   _VALIDATE_RETURN(("'n' format specifier disabled", 0), EINVAL, -1);
   break;
}

这带来了这个:

替代文字 http://www.shiny.co.il/shooshx/printfn.png

对于以下行:

    printf ("%s other stuff: %n", thing, &len);

我猜这主要是为了避免@eJames所说的

于 2008-12-09T18:46:58.713 回答
0

你可以打电话

int _get_printf_count_output();

查看是否启用了 %n 支持,或使用

int _set_printf_count_output( int enable );

启用或禁用对 %n 格式的支持。

来自 MSDN VS2008

于 2010-04-27T13:02:37.577 回答