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;
}
At first you have to include header
<stdio.h>:If you call the function with the second parameter equal to
LINELIMthen
line1has to be defined with the same sizeAs for me I would rewrite function
getlinethe following way:)The main loop in main can be written like
You should move the declaration of
ifrom main inside the while loop because except this while loop the variable is not used anywhere in main.As for your code then setting
itolen - 2is incorrect.Let's assume that the
line1contains only the new line character'\n'. In this caselenis equal to1and as result i will be equal to-1. So the trailing new line character will not be removed.