[英]sprintf format specifier replace by nothing
I am currently wondering if there is a way to replace the format specifier %u by nothing using sprintf 我目前在想是否有办法使用sprintf替换格式说明符%u而不用
My question is about the use of a ternary operator in sprintf which gonna replace %u by a value or by nothing. 我的问题是在sprintf中使用三元运算符,该运算符将%u替换为值或不替换任何内容。
Here is an example of what I am trying to do : 这是我要执行的操作的一个示例:
int main (void)
{
char mytab[10]={'\0'};
uint_32 i=0;
scanf("%u",&i);
sprintf(mytab, "\"%u"\",i>0?i:/*Here is the syntax I want to find if it exists*/);
printf("%s\r\n",mytab);
return 0;
}
The result of the code I am trying to get is for example "1" if the input is 1 (or "2" if the input is 2...) and "" if the input is 0. 我尝试获取的代码结果例如是:如果输入为1,则为“ 1”(如果输入为2 ...,则为“ 2”),如果输入为0,则为“”。
Do you have any ideas or explantion about it ? 您对此有什么想法或看法吗? Thanks by advance.
预先感谢。
我认为您应该将三进制运算符放在格式字符串上,根据i的值选择使用"%u"
或""
。
sprintf(mytab, i? "\"%u\"" : "\"\"", i);
Modify this statement 修改此语句
sprintf(mytab, "\"%u"\",i>0?i:/*Here is the syntax I want to find if it exists*/);
This is what you need. 这就是你所需要的。
(i>0)? sprintf(mytab, "%u",i) : sprintf(mytab,"%s","") ;
EDIT 编辑
AS H2CO3 suggested 建议使用H2CO3
You can also Use in this way. 您也可以这种方式使用。
if (i > 0)
sprintf(mytab, "%"PRIu32, i);
else
sprintf(mytab,"%s","");
Also note that %u
is not the appropriate format specifier for uint32_t
, use "%"PRIu32
另请注意,
%u
不是uint32_t
的适当格式说明符,请使用"%"PRIu32
(i>0)? sprintf(mytab, "%"PRIu32,i) : sprintf(mytab,"%s","") ;
I think a simple if
statement is still the cleanest option: 我认为简单的
if
语句仍然是最干净的选择:
char mytab[10] = "\"\"";
if (n > 0) {
snprintf(mytab, sizeof mytab, "\"%" PRIu32 "\"", n);
}
You might (not?) like to use this dirty trick *1 (which makes gcc yell out warnings): 您可能(不是?)喜欢使用这个肮脏的把戏* 1 (这会使gcc大喊警告):
char mytab[11] = "";
uint32_t i = 0;
int result = scanf("%"SCNu32, &i);
if (1 != result)
{
if (-1 == result)
{
if (errno)
{
perror("scanf() failed");
}
else
{
fprintf(stderr, "EOF reached\n");
}
}
else
{
fprintf(stderr, "invalid input\n");
}
}
sprintf(mytab, i>0 ?"%"PRIu32 :"%s", i>0 ?i :"");
printf("%s", mytab);
*1 To mention this explicitly: "dirty" in this context is a hint that this might invoke the fabulous Undefined Behaviour. * 1明确提及这一点:在此上下文中,“脏”是暗示这可能会调用神话般的Undefined Behaviour。 So don't do this in prodcution!
因此, 请勿在生产中这样做 !
The sane apporach would be to do: 理智的方法是:
...
if (i)
{
sprintf(mytab, "%"PRIu32, i);
}
printf("%s", mytab);
Please note that although the maximum number of digits for an unsigned 32bit number in decimal format is 10, you still need to reserve one character for the 0
-terminator. 请注意,尽管十进制格式的无符号32位数字的最大位数为10,但仍需要为
0
终止符保留一个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.