是否有在的printf / scanf家族中的格式%N的任何实际应用?
题
int x;
printf("hello %n World\n", &x);
printf("%d\n", x);
解决方案
这不是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
...
}
其他提示
它可以被用来执行作恶的。
要看你的实际意思。总是有其他的方法来完成它(打印与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编译器)
这是只是尽可能对准事物的一种方式实用,但我不希望看到它的代码。有这样做的更好的方法。
这是相当深奥。如果您需要将生成的字符串替换占位符后,你可能要记住一个字符串索引的中间,让你不必要么保存原始的printf参数或解析字符串。
有可能被用作快速的方式来获得各个子串的长度。
#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;
}
我在这里失去了一些东西是肯定的。蕃茄太远到右侧。
下面是来自CRT VS2005代码的内容:
/* 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谈论
可以调用
int _get_printf_count_output();
,以查看是否%正支持使能,或使用
int _set_printf_count_output( int enable );
要启用或禁用支持%N的格式。
这MSDN VS2008
不隶属于 StackOverflow