我如何使用strlen()上的格式化字符串? [英] How do I use strlen() on a formatted string?

查看:164
本文介绍了我如何使用strlen()上的格式化字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个包装函数在 mvwprint / mvwchgat的ncurses 功能,它打印在指定的窗口中的消息,然后改变其属性。

I'd like to write a wrapper function for the mvwprint/mvwchgat ncurses functions which prints the message in the specified window and then changes its attributes.

然而, mvwchgat 的需要知道它应该有多少个字符改变 - 我不知道该如何告诉的 mvwchgat 的格式化字符串有多长,因为 strlen的()的上,例如,ABC%D显然返回5,因为的的strlen 的不知道是什么%d个表示...

However, mvwchgat needs to know how many characters it should change - and I have no idea how to tell mvwchgat how long the formatted string is, since a strlen() on, for instance, "abc%d" obviously returns 5, because strlen doesn't know what %d stands for ...

推荐答案

在C99或C11,你可以用这样一行:

In C99 or C11, you can use a line like this:

length = snprintf(NULL, 0, format_string, args);

的snprintf 手册一>(重点煤矿):

From the manual of snprintf (emphasis mine):

功能的snprintf()和vsnprintf()不写比大小字节(包括结尾的空字节('\\ 0'))等等。 如果输出是由于这个限制截断则返回值是字符这将被写入最后的字符串,如果有足够的空间已经可用的数(不包括终止空字节)。因此,大小或更大的返回值意味着输出被截断。

The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')). If the output was truncated due to this limit then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated.

由于我们给的snprintf 0的大小,则输出始终是截断和的snprintf 的输出将是字符的数目将的已被写入,这基本上是串的长度。

Since we are giving snprintf 0 as the size, then the output is always truncated and the output of snprintf would be the number of characters that would have been written, which is basically the length of the string.

在C89,你不必的snprintf 。一种解决方法是创建一个临时文件,或者如果你是在* nix中打开的/ dev / null的,写是这样的:

In C89, you don't have snprintf. A workaround is to create a temporary file, or if you are in *nix open /dev/null and write something like this:

FILE *throw_away = fopen("/dev/null", "w"); /* On windows should be "NUL" but I haven't tested */
if (throw_away)
{
    fprintf(throw_away, "<format goes here>%n", <args go here>, &length);
    fclose(throw_away);
} /* else, try opening a temporary file */

这篇关于我如何使用strlen()上的格式化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆