简体   繁体   中英

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

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;
}

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 (ie 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 ;
}

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;
}

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM