Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Exercise 1-18.
- * 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 /* maximum input line length */
- int
- get_line(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;
- }
- int
- chomp(char* str) {
- int i,j;
- i = 0;
- j = -1;
- /* handle empty string as a especial case */
- if (str[i] == '\0')
- return 0;
- while (str[i] != '\0') {
- if (str[i] != ' ' && str[i] != '\t' && str[i] != '\n') {
- j = i;
- }
- i++;
- }
- /*
- * if the string is nothing but blanks,
- * then terminate it
- */
- if (j < 0 ) {
- str[0] = '\0';
- return 0;
- }
- /*
- * if there is a gap, just insert '\n' before terminating the string
- * otherwise, the string is already free of tail blanks
- */
- if (i > j + 1) {
- str[j+1] = '\n';
- str[j+2] = '\0';
- }
- return j+1;
- }
- int
- main()
- {
- int len;
- char line[MAXLINE];
- /* current line length */
- /* maximum length seen so far */
- while ((len = get_line(line, MAXLINE)) > 0) {
- chomp(line);
- printf("%s",line);
- }
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment