C 语言有 setfill() 替代方案吗?
在 C++ 中:
int main()
{
cout << setfill('#') << setw(10) << 5 << endl;
return 0;
}
输出:
#########5
C 是否有任何 setfill()
替代方案?或者如何在 C 中执行此操作而无需手动创建字符串?
In C++:
int main()
{
cout << setfill('#') << setw(10) << 5 << endl;
return 0;
}
Outputs:
#########5
Is there any setfill()
alternative for C? Or how to do this in C without manually creating the string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将输出:
0000000005
现在,如果您确实想要“#”而不是“0”,则必须在字符串中手动替换它们。
或许 :
will output :
0000000005
Now if you really want '#' instead of '0' you'll have to replace them manually in the string.
Maybe :
不,没有直接的替代方案。
但是,如果您有一个行为良好的
snprintf
(其行为符合 C99 标准所描述的),则无需创建新字符串即可工作;仅创建 2 个临时int
编辑:在 ideone 运行版本。
EDIT2:C99 标准的
snprintf
和 Windows_snprintf
之间的差异(感谢您的链接,Ben):int snprintf( char *限制缓冲区, size_t n, const char *限制格式, ...);
int _snprintf(char *buffer, size_t n, const char *format, ...);
code>snprintf
写入不超过 (n-1) 个字节,NUL_snprintf
写入不超过 (n) 个字节,最后一个可能是 NUL 或其他字符snprintf
返回格式所需的字符数(可以大于n
)或-1
,以防编码错误_snprintf<如果
n
对于字符串来说不大,/code> 返回负值;或n
如果 NUL 字节尚未写入缓冲区。您可以在循环中运行行为不当的
_snprintf
,增加n
直到找到正确的值No, there is no direct alternative.
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 temporaryint
sEDIT: running version at ideone.
EDIT2: Differences between the C99 Standard's
snprintf
and Windows_snprintf
(thank you for the link, Ben):int snprintf(char *restrict buffer, size_t n, const char *restrict format, ...);
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.You can run the mis-behaving
_snprintf
in a loop, increasingn
until you find the right value每个人都想调用
printf
两次...printf
是最昂贵的函数之一。这里:
Everybody wants to call
printf
twice...printf
is one of the most expensive functions around.Here:
不是按照标准内置的,
我可能会 sprintf() 将数字转换为字符串并获取字符数,然后在打印字符串之前首先输出正确的“#”数量。
Not built in as standard
I would probably sprintf() the number to a string and get the count of characters then output the correct number of '#' first before printing the string.
下面将使用 C 中的
memset
来完成此操作(假设为 1 字节字符)。它仍然创建一个“字符串”,尽管我不确定您不希望它是多么手动。根据您实际想要用它做什么,您可以动态创建适当大小的缓冲区,并根据需要从辅助函数返回它。
The following will do it using
memset
in C assuming a 1-byte char. It still creates a 'string', though I'm not sure how manually you don't want it to be.Depending what you want to actually do with it, you could dynamically create the buffer to be the appropriate size and return it from a helper function if you so desire.