在C中的输出的末尾删除空白 [英] Remove white space at the end of the output in C

查看:149
本文介绍了在C中的输出的末尾删除空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code是用于打印在螺旋的次序的矩阵的元素。该项目工程的罚款。但问题是,在线编译器对其中我检查程序,不接受在输出末尾的尾随空格。任何人都可以给我一些想法,我怎么能找到解决的最后一个空白在输出被添加?

The following code is for printing the elements of a matrix in spiral order. The program works fine. The problem, however, is that the online compiler against which I'm checking the program, doesn't accept trailing white spaces at the end of the output. Could anyone give me some ideas as to how I can get around the last white space being added at the output?

有关参考,我的code是如下(是变量名是可怕的。我正在努力改变我的推杆随机变量名的习惯!)

For reference, my code is as follows (yes the variable names are terrible. I'm working on changing my habit of putting random variable names!!)

#include <stdio.h>
int main()
{
    int a[6][6];
    int i, k = 0, l = 0, m=3, n=3, j;
    scanf("%d %d",&m, &n);
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
            scanf("%d",&a[i][j]);
    }
    while (k < m && l < n)
    {
        for (i = l; i < n; ++i)
            printf("%d ", a[k][i]);
        k++;
        for (i = k; i < m; ++i)
            printf("%d ", a[i][n-1]);
        n--;
        if ( k < m)
        {
            for (i = n-1; i >= l; --i)
                printf("%d ", a[m-1][i]);
            m--;
        }
        if (l < n)
        {
            for (i = m-1; i >= k; --i)
                printf("%d ", a[i][l]);
            l++;
        }
    }
    return 0;
}

输入:

1 2 3

4 5 6

7 8 9

输出:

1 2 3 6 9 8 7 4 5{one extra space}

有办法解决这个问题呢?
(也可用于可怕的格式抱歉。在计算器上首先的问题!)

Any way to fix this problem? (Also sorry for the terrible formatting. First question on StackOverflow!)

推荐答案

看你的code,这个(第一个在,而循环):

Looking at your code, this for (the first one in the while loop):

for (i = l; i < n; ++i)
    printf("%d ", a[k][i]);

将总是至少那些执行(因为 L&LT; N ,从,而的病情来)

然后,你可以做到以下几点:

Then you can just do the following:


  • 总是在号码前加空格

  • 添加一个如果检查只为这第一个 -loop(使用一些布尔标志)。

  • always add the space in front of the number
  • add a single if check just for this very first for-loop (use some bool flag).

例如,是这样的:

bool first = true;
while (k < m && l < n)
{
    for (i = l; i < n; ++i)
    {
        if( ! first )
        {
            printf(" %d", a[k][i]);
        }
        else
        {
            printf("%d", a[k][i]);
            first = false;
        }
    }
    // ....
}

这将是相当有效和短期的解决方案 - 如果是在短短的一环,该标志将是真正只有一次(将避免缓存未命中)。

This will be rather efficient and short solution - the if is in just one loop and the flag will be true just once (will avoid cache misses).

这篇关于在C中的输出的末尾删除空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆