Home > Software design >  How i can remove the last comma from the output? in c
How i can remove the last comma from the output? in c

Time:07-26

#include<stdio.h>   
#include<unistd.h>

void ft_putchar(char x, char y, char z){
    write(1, &x, 1);
    write(1, &y, 1);
    write(1, &z, 1);
}
void ft_print_comb()
{
    char i, j, k;
    i = '0';
while (i <= '7') {
    j = i   1;
    while (j <= '8') {
        k = j   1;
        while (k <= '9') {
            if(i =='7' && j=='8') */ i created this section to remove comma*/
            {
                ft_putchar('7', '8', '9');
                write(1, '1 ', 1);
            }
            else
                ft_putchar(i, j, k);
                write(1, ", ", 2);
                k  ;
        }
        j  ;
    }
    i  ;
}
}
int main(){
    ft_print_comb();
    return 0;
}

i wrote a code for creating a function that displays all different combinations of three different digits in ascending order, listed by ascending order but i don't know how to remove the last comma from the output? end of my output looks like this

579, 589, 678, 679, 689, 789,

CodePudding user response:

The simplest way to do this is to always print the comma first, but not on the first iteration.

int first = 1;
while (i <= '7') {
    j = i   1;
    while (j <= '8') {
        k = j   1;
        while (k <= '9') {
            if (!first) {
                write(1, ", ", 2);
            } else {
                first=0;
            }
            ft_putchar(i, j, k);
            ...

CodePudding user response:

You can write the comma and space before each number except the first. A boolean flag can be used to indicate whether it is the first output.

#include <stdbool.h>
// ...
bool first = true;
while (i <= '7') {
    j = i   1;
    while (j <= '8') {
        k = j   1;
        while (k <= '9') {
            if (first) first = false;
            else write(1, ", ", 2);
            ft_putchar(i, j, k);
            k  ;
        }
        j  ;
    }
    i  ;
}
  • Related