|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Be the architects of evolution and help create the mobile internet future. It’s your move---enter to win here! |
|
#1
|
|||
|
|||
|
stuck on one of the k&r exercises
i'm currently learning c by following 'the c programming language' by kernighan and ritchie.
i'm stuck on one of the exercises that says 'write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines' my effort follows but it isn't working. i've also added a bit to remove trailing e's, just so i can see if it works or not because i can't tell if it's deleting spaces. if this is inputted: afsdf asdfaseee it outputs this: afsdf asdfas ee so the added '\n' and i assume the added '\0' is in fact being being added and in the right place, but it doesn't seem to have the desired effect - in particular the '\0' which was supposed to resemble the end of the line. what am i doing wrong? Code:
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */
int getline(char line[], int maxline);
void tidy(char line[], int length);
/* print longest input line*/
main()
{
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
max=0;
while((len=getline(line, MAXLINE))>0) {
tidy(line, len);
printf("%s", line);
}
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;
}
void tidy(char line[], int len)
{
int i;
i=len-1;
while (line[i]==' ' || line[i]=='\t' || line[i]=='e' || line[i]=='\n')
--i;
if (i!=-1)
line[++i]='\n';
line[++i]=='\0';
}
|
|
#2
|
|||
|
|||
|
forget this. i made a stupid mistake - a double equals in the last line. silly me.
|
|
#3
|
|||
|
|||
|
You can also save yourself a little trouble by eliminating the getline function and using the standard library function fgets() instead. It does exactly what you're doing in getline and would shorten your code.
In your tidy function, it's worth the effort to investigate the isspace macro, defined in ctype.h That would also save you a good deal of code. In both cases these functions are documented by the man pages, even if you haven't encountered them in the K&R book yet.
__________________
Clay Dowling Lazarus Notes Articles and commentary on web development http://www.lazarusid.com/notes/ |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > stuck on one of the k&r exercises |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|