Reputation: 2667
I am trying to write a program that removes trailing spaces/tabs from input lines (Exercise 1-18 from K&R).
/* 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);
main()
{
int len, i;
char line[MAXLINE];
while ((len = gettline(line, MAXLINE)) > 0)
for(i=0; i<len-1; ++i){
if (line[i]!= ' ' && line[i]!='\t')
printf("%s", 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;
}
When I run it I get the error Segmentation fault (core dumped)
. I viewed some other SO questions with the same theme (1, 2, 3, 4,..) but they were too complex for my level. I only know that the error means I tried to access part of the memory I wasn't allowed to. I am not sure where exactly this happened in my case
Upvotes: 1
Views: 3533
Reputation: 9884
The reason for the seg fault should be this:
for(i=0; i<len-1; ++i){
if (line[i]!= ' ' && line[i]!='\t')
printf("%s", line[i]);
}
Because of %s
, printf()
expects a char *
argument but you pass a single character.
Change it to printf( "%c", line[i] );
and it should run.
But it still wouldn't do what you say you want to achieve ("remove trailing spaces/tabs") because you wouldn't print any spaces or tabs, " Hello World " would become "HelloWorld"
Upvotes: 3