I am currently wondering if there is a way to replace the format specifier %u by nothing using sprintf
My question is about the use of a ternary operator in sprintf which gonna replace %u by a value or by nothing.
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.
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
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
(i>0)? sprintf(mytab, "%"PRIu32,i) : sprintf(mytab,"%s","") ;
I think a simple if
statement is still the cleanest option:
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):
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.