代码之家  ›  专栏  ›  技术社区  ›  EvilTeach

printf/scanf系列中的%n格式是否有实际应用?

  •  17
  • EvilTeach  · 技术社区  · 17 年前
    int x;
    printf("hello %n World\n", &x);
    printf("%d\n", x);
    
    8 回复  |  直到 17 年前
        1
  •  15
  •   Adam Rosenfield    17 年前

    这对我来说没什么用处 printf() sscanf() ,尤其是在多次迭代中解析字符串时。 fscanf() scanf() 根据输入读取量自动推进其内部指针,但 没有。例如:

    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
        ...
    }
    
        2
  •  5
  •   James Eichele Bernard Igiri    17 年前

    它可以用来执行 evil deeds

        3
  •  4
  •   The Archetypal Paul    17 年前

    然而

    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编译器)

    这是一种很实用的方法来协调事情,但我不想在代码中看到它。有更好的方法。

        4
  •  3
  •   Darron    17 年前

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

        5
  •  1
  •   Richard J. Ross III    14 年前

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

        6
  •  1
  •   EvilTeach    13 年前
    #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;
    }
    

    我肯定错过了一些东西。汤姆托斯离右边太远了。

        7
  •  0
  •   shoosh    17 年前

    以下是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;
    }
    

    这就引出了这个问题:

    alt text http://www.shiny.co.il/shooshx/printfn.png

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

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

        8
  •  0
  •   yur    16 年前

    你可以打电话

    int _get_printf_count_output();
    

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

    int _set_printf_count_output( int enable );
    

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