Home > Mobile >  How to remove \n of fgets function, without using string functions
How to remove \n of fgets function, without using string functions

Time:05-09

Is there a way to remove the \N character from the end of the string reading with fgets, without using string processing functions (strlen, strtok, strcspn, etc) ? I tried that, but it doesn't work

char* remove_newline_char(char *str){
    for(int i = 0; i < str[i]; i  ){
        if(str[i] == '\n'){
            str[i] = '\0';
        }
    }
    return str;
}

CodePudding user response:

Your code is semantically incorrect. the loop termination expression i < str[i] says:

is the string index less than the character value at that index?

which is of course nonsense - the index and the character value are unrelated.

char* remove_newline_char(char* str)
{
    int i = 0 ;
    while( str[i] != 0 && str[i] != '\n' )
    {
        i   ;
    }
    str[i] = 0 ;

    return str ;
}

Given that this processing is specific to buffers populated by fgets() rather then a generic string function, there may be merit in combining the input with the processing so that it will not be applied to inappropriate strings (i.e. not from fgets()):

char* freadline( char* str, int num, FILE* stream )
{
    char* ret = NULL ;

    if( (ret = fgets( str, num, str )) != NULL )
    {
        int i = 0 ;
        while( str[i] != 0 && str[i] != '\n' )
        {
            i   ;
        }
        str[i] = 0 ;
     }
     return ret ;
}

CodePudding user response:

You don't need to transverse through the full array and check for each character at every iteration.

As, you have stated don't use string functions, I'm not using strlen() function.

In fgets() newline character is present at length - 1 position.

char* remove_newline_char(char *str){
    size_t len = 0;
    while (str[len])
        len  ;
    if(str[len - 1] == '\n')
        str[len - 1] = 0;
    return str;
}

Also, if you know the length of string, then you can avoid that while loop

char* remove_newline_char(char *str, size_t len){
    if(str[len - 1] == '\n')
        str[len - 1] = 0;
    return str;
}

CodePudding user response:

Of course my loop was wrong. Here's the version that works

char* remove_newline_char(char *str){
for(int i = 0; str[i]; i  ){
    if(str[i] == '\n'){
        str[i] = '\0';
    }
}
return str;

}

  •  Tags:  
  • c
  • Related