trailing char end of line still gives 0920 at the end of first line

86 Views Asked by At

Task is to delete spaces and tabs from the end of input line maintaining line count. Can't use string library. I've done all I could have and still in output file there is 0920 at the end of the first line (using octal dump od -x trim.out) any ideas what else might be wrong with it???

#define LINELIM 1000

int getLine(char s[], int lim);

int main (void){
    int  len, i;
    char line1[100];

    while ((len = getLine(line1, LINELIM)) >0){
            for (i=len-2; i>=0; i--){
            if (line1[i] == ' ' || line1[i] == '\t' || line1[i] == '\n'){
                   // professor says it is always true for some reason
                line1[i] = '\0';
            }
            else break;
        }

    if(line1[0]) // not a blank
        printf(" %s\n", line1);
    }

return 0;
}
/*getline: read a line into s, return length*/
int getLine(char s[], int lim){
    int c,i;
    for (i=0; i<lim-1 && (c=getchar())!= EOF && c!='\n'; ++i)
        s[i]=c;
    if (c == '\n'){
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}
1

There are 1 best solutions below

2
On

At first you have to include header <stdio.h>:

#include <stdio.h>

If you call the function with the second parameter equal to LINELIM

getLine(line1, LINELIM)

then line1 has to be defined with the same size

char line1[LINELIM];

As for me I would rewrite function getline the following way:)

int getLine( char s[], int lim )
{
    int c;

    int i = 0;

    while ( i < lim - 1 && ( c = getchar() ) != EOF && ( s[i++] = c ) !='\n' ); 

    s[i] = '\0';

    return i;
}

The main loop in main can be written like

while ( ( len = getLine( line1, LINELIM ) ) > 0 )
{
    int i = len;

    while ( i != 0 && ( line1[i-1] == ' ' || line1[i-1] == '\t' || line1[i-1] == '\n' ) ) --i;

    line1[i] = '\0';

    if ( line1[0] ) printf( "%s\n", line1 );
}

You should move the declaration of i from main inside the while loop because except this while loop the variable is not used anywhere in main.

As for your code then setting i to len - 2 is incorrect.

for (i=len-2; i>=0; i--){
     ^^^^^^

Let's assume that the line1 contains only the new line character '\n'. In this case len is equal to 1 and as result i will be equal to -1. So the trailing new line character will not be removed.