Home > Net >  How do you delete the comma after the number?
How do you delete the comma after the number?

Time:09-15

So I have this exercise from my Coding class and we were tasked to input the user's input. However, we have to remove the comma of the last number of our output, and I'm struggling with how to remove that comma. Can anyone please help?

this is my code

#include <stdio.h>

#define MAX_SIZE 100 

int main(){
    int arr[MAX_SIZE];
    int N, i;
    int * ptr = arr;    
    
    printf("Enter length: ");
    scanf("%d", &N);

    for (i = 0; i < N; i  ){
        printf("Enter element %d: ", i 1);
        scanf("%d", ptr);
        ptr  ;   
    }

    ptr = arr;

    printf("[");
    for (i = 0; i < N; i  )
    {
        printf("%d,", *ptr);

        ptr  ;
    }

        printf("]");

    return 0;
}

for convenience, this is the output I got

Enter length: 5
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
[1,2,3,4,5,]

this is how the output should be

Enter length: 5
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
[1,2,3,4,5]

CodePudding user response:

Simple:

const char *sep = "";
printf( "[" );
for( i = 0; i < N; i   ) {
    printf( "%s%d", sep, arr[ i ] );
    sep = ",";
}
printf( "]" );

Put the commas BEFORE the next value to be printed. Specify the "prefix" to be "", until that is changed to ","

You'd be better off using "array indexing" throughout instead of shifting a pointer around the place... Too easy to forget to reset it to the beginning...

AND, add some code to check that scanf has assigned an integer value to the uninitialised variable 'N'! If the user types "four" in response to the first prompt, the value of N could be anything, even 243,478,658.... That's a LOT of data to be entering... In addition, the code should also check if the user types 120 to fill the 100 elements of the array.

CodePudding user response:

You can use a simple ternary to control the format-string in printf, e.g.

    for (i = 0; i < N; i  )
    {
        printf(i ? ",%d" : "%d", *ptr);

        ptr  ;
    }

That only prints a comma before the number for numbers after the first. An equivalent long-form using if-else would be:

    for (i = 0; i < N; i  )
    {
        if (i) {
            printf(",%d", *ptr);
        }
        else {
            printf("%d", *ptr);
        }
        
        ptr  ;
    }

Also suggest the final puts ("]"); to ensure your program is POSIX compliant -- outputting a final '\n' before program exit. Likewise, there is no need to call the variadic printf() function to output a single-character. A simple putchar ('['); will do.

  •  Tags:  
  • c
  • Related