有C的setfill()替代方法吗? [英] Is there any setfill() alternative for C?
问题描述
在C ++中:
int main()
{
cout << setfill('#') << setw(10) << 5 << endl;
return 0;
}
输出:
#########5
C是否有任何 setfill()
替代方案?还是在C中无需手动创建字符串就可以做到这一点?
Is there any setfill()
alternative for C? Or how to do this in C without manually creating the string?
推荐答案
不,没有直接的选择.
但是,如果您具有良好的 snprintf
(其行为符合C99标准的描述),则无需创建新字符串即可工作;仅创建2个临时 int
s
But if you have a well-behaved snprintf
(one that behaves as described by the C99 Standard), this works without creating a new string; creating only 2 temporary int
s
#include <stdio.h>
int main(void) {
int filler = '#'; /* setfill('#') */
int width = 10; /* setw(10) */
int target = 5; /* 5 */
/* ******** */
int s = snprintf(NULL, 0, "%d", target);
for (int i = 0; i < width - s; i++) {
putchar(filler);
}
printf("%d\n", target);
/* ******** */
return 0;
}
运行版本为 ideone .
C99 Standard的 snprintf
和Windows _snprintf
之间的区别(感谢您的链接,Ben ):
Differences between the C99 Standard's snprintf
and Windows _snprintf
(thank you for the link, Ben):
- 原型:
int snprintf(char *限制缓冲区,size_t n,const char *限制格式,...);
- 原型:
int _snprintf(char * buffer,size_t n,const char * format,...);
-
snprintf
最多写入(n-1)个字节和一个NUL -
_snprintf
最多写入(n)个字节,最后一个字节可以是NUL或其他字符 -
snprintf
返回格式所需的字符数(可以大于n
)或-1
(如果出现编码错误) 如果 -
_snprintf
返回负值;否则,返回负数.或n
(如果尚未将NUL字节写入缓冲区).
n
对于字符串来说不大,则- prototype:
int snprintf(char *restrict buffer, size_t n, const char *restrict format, ...);
- prototype:
int _snprintf(char *buffer, size_t n, const char *format, ...);
snprintf
writes no more than (n-1) bytes and a NUL_snprintf
writes no more than (n) bytes, the last of which may be NUL or other charactersnprintf
returns the number of characters needed for format (can be larger thann
) or-1
in case of encoding error_snprintf
returns a negative value ifn
is not large for the string; orn
if a NUL byte hasn't been written to buffer.
您可以循环运行行为不正确的 _snprintf
,增加 n
直到找到正确的值
You can run the mis-behaving _snprintf
in a loop, increasing n
until you find the right value
/* absolutely not tested, written directly on SO text editor */
int i;
size_t rightvalue = 0;
char buffer[SOME_DEFAULT_VALUE];
do {
if (sizeof buffer < rightvalue) /* OOPS, BIG BIG OOPS */;
i = _snprintf(buffer, rightvalue, "%d", 42);
} while (i != rightvalue++);
/* rightvalue already has space for the terminating NUL */
这篇关于有C的setfill()替代方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!