c - Removing spaces from the two sides of a text line -


i supposed write simple program strips lines of trailing spaces , tabs. should written basic tools in c (no pointers , libraries).

/* write program remove trailing blanks , tabs each line of input, , delete entirely blank lines. */  #include <stdio.h> #define maxline 1000  int gettline(char s[], int lim); void inspect_line(char s[], int limit, int start, int end);  main() {     int len, i, start, end;     start = 0;     end = maxline;     char line[maxline];     while ((len = gettline(line, maxline)) > 0){             inspect_line(line, maxline, start, end);             for(i=start; i<end-1;++i)                 printf("%c",line[i]);         }     printf("\n");        return 0; }  /* gettline: read line s, return length */ int gettline(char s[], int lim) {     int c, i;     (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; }  /* inspect_line: determines indices start , end of sentence */ void inspect_line(char s[], int limit, int start, int end) {     while((s[start]!=' ') && (start<limit-1))         ++start;     while(!(s[end]>=33 && s[end]<=126))         --end; } 

when run it, strange result:

enter image description here

i not sure problem , have been trying debug hours no result.

here going on: when write

inspect_line(line, maxline, start, end); for(i=start; i<end-1;++i)     printf("%c",line[i]); 

you assume values set start , end inside inspect_line function transferred main; assumption incorrect. in c parameters passed value. why start , end remain before call.

you can fix passing pointers start , end inspect_line function. of course need change function accept , use pointers, too:

void inspect_line(char s[], int *start, int *end) {     while(isspace(s[*start]) && (*start < *end))         ++(*start);     while(isspace(s[*end]) && (*start < *end))         --(*end); } 

the call this:

// note passing maxline no longer necessary inspect_line(line, &start, &end); for(i=start ; <= end-1 ; ++i) // both start , end inclusive     printf("%c",line[i]); 

you need re-initialize start , end between each iteration of loop, setting start 0 , end current value of len.


Comments