Home > database >  Program to remove \n characters ,2 ways to do the same idea but have different results
Program to remove \n characters ,2 ways to do the same idea but have different results

Time:11-23

first program

#include "stdio.h"
#include "string.h"
void delete_n(char x[]){
    int len = strlen(x);
    // TITV\n\0 => TITV\0\0
    if(x[len-1]=='\n'){
        x[len-1]='\0';
    }
}

int main(){

    char name[50];
    printf("your name: ");
    fgets(name, sizeof(name), stdin);
    delete_n(name);
    printf("\nYour name : %s", name);
    printf("\nlen = %d", strlen(name));
    

}

2nd program

#include "stdio.h"
#include "string.h"
void delete_n(char x[]){
    int len = strlen(x);
    // TITV\n\0 => TITV\0\0
    if(x[len]=='\n'){
        x[len]='\0';
    }
}

int main(){

    char name[50];
    printf("your name: ");
    fgets(name, sizeof(name), stdin);
    delete_n(name);
    printf("\nYour name : %s", name);
    printf("\nlen = %d", strlen(name));
    

}

why is the length of the string in the 2nd program unchanged as in the first program

both programs aim to delete \n then measure the length of the string

this is images you can see result

enter image description here

CodePudding user response:

The second program does not remove the \n. You can test it yourself

int main(){

    char name[50];
    printf("your name: ");
    fgets(name, sizeof(name), stdin);
    delete_n(name);
    for(char *p = name; *p; p  )
    {
        printf("%d ", *p);
    }
    printf("\n");
}

https://godbolt.org/z/5GWK48rcc

your name: 84 73 84 86 10 

The first function is also incorrect. It will fail if the string is 0 chars long. The type for length is also wrong.

void delete_n(char *x)
{
    if(x && *x)
    {
        size_t len = strlen(x);
        if(x[len - 1]=='\n')
        {
            x[len - 1]='\0';
        }
    }
}

CodePudding user response:

if(x[len]=='\n') is always false, so 2nd program does not remove any '\n'.

Given int len = strlen(x);, x[len] contains '\0'.


Corner cases: x[len-1] risks undefined behavior (UB) should fgets() as len == 0 is possible. Uncommonly, fgets() may first read a _null character.

//if(x[len-1]=='\n'){
// Better as 
if(len > 0 && x[len-1] == '\n'){
    x[len]='\0';
}

or use

// Remove trailing \n if there or not.
x[strcspn(x, "\n")] = '\0';
  •  Tags:  
  • c
  • Related