![](/img/trans.png)
[英]How to remove the final "%" sign from the output in c with printf()
[英]How to remove last space from printf output
我通过间隙打印出数组的每个元素
// n - array length
for(x=0; x<n; x++){
printf("%d ", a[x]);
}
它返回我:
1 2 3 4 5 [space here]
如何删除最新空格(字符)?
for(x=0; x<n; x++){
if(x == n-1)
printf("%d", a[x]); /* Print without space when printing last element */
else
printf("%d ", a[x]);
}
恕我直言,一种更具可读性的替代方法:
for ( x = 0; x < n; x++ )
{
if (x > 0)
putchar(' ');
printf("%d", a[x]);
}
方法很简单:
for(x=0; x<n; x++){
printf("%d", a[x]);
if(x<(n-1)){
printf(" ");
}
}
for(x=0; x<n-1; x++){
printf("%d ", a[x]);
}
if(n > 0)
printf("%d", a[x]);
Paul Roub解决方案的“无分支”变体。 它要求n > 0
成立(即因此存在在至少一个元件a
阵列)。
#include <stdio.h>
int main(void)
{
int x, n, a[] = {1, 2, 3, 4, 5};
n = 5;
printf("%d", a[0]);
for (x = 1; x < n; x++)
printf(" %d", a[x]);
putchar('\n');
return 0;
}
每个人都在发布自己的答案,所以这是我自己的答案。
int n, i;
for (i = 1, n = 5; i <= n; i++)
printf("%d%s", i, i < n ? " " : "");
不知道我会推荐这种方法,但是类似的东西也可以工作:
for ( x = 0; x < n; x++ )
{
printf("%c%d", " "[!x], a[x]);
}
这有点作弊,但我认为它很整洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.