Reputation: 2667
I am supposed to write a simple program that strips the lines of their trailing spaces and tabs. It should be written with the most basic tools in C (No pointers and libraries).
/* Write a program to remove trailing blanks and tabs from each
line of input, and to 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 a line into s, return length */
int gettline(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;
}
/* inspect_line: determines the indices to the start and the end of the 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 I run it, I get a strange result:
I am not sure what the problem is and I have been trying to debug it for hours with no result.
Upvotes: 1
Views: 53
Reputation: 726669
Here is what is going on: when you write
inspect_line(line, MAXLINE, start, end);
for(i=start; i<end-1;++i)
printf("%c",line[i]);
you assume that the values set to start
and end
inside inspect_line
function would be transferred to main
; that assumption is incorrect. In C parameters are passed by value. That is why start
and end
remain what they were before the call.
You can fix this by passing pointers to start
and end
into the inspect_line
function. Of course you would need to change the function to accept and 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 would look like this:
// Note that passing MAXLINE is no longer necessary
inspect_line(line, &start, &end);
for(i=start ; i <= end-1 ; ++i) // both start and end are inclusive
printf("%c",line[i]);
You would also need to re-initialize start
and end
between each iteration of the loop, setting start
to zero and end
to the current value of len
.
Upvotes: 2