khalfella

ansi_c_pg31_ch01_ex18.c

Sep 26th, 2014
311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. /*
  2. * Exercise 1-18.
  3. * Write a program to remove trailing blanks and tabs from each line of input,
  4. * and to delete entirely blank lines.
  5. */
  6.  
  7.  
  8. #include <stdio.h>
  9. #define MAXLINE 1000 /* maximum input line length */
  10.  
  11. int
  12. get_line(char s[], int lim) {
  13. int c, i;
  14. for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
  15. s[i] = c;
  16. if (c == '\n') {
  17. s[i] = c;
  18. ++i;
  19. }
  20. s[i] = '\0';
  21. return i;
  22. }
  23.  
  24. int
  25. chomp(char* str) {
  26. int i,j;
  27.  
  28. i = 0;
  29. j = -1;
  30.  
  31.  
  32. /* handle empty string as a especial case */
  33. if (str[i] == '\0')
  34. return 0;
  35.  
  36. while (str[i] != '\0') {
  37. if (str[i] != ' ' && str[i] != '\t' && str[i] != '\n') {
  38. j = i;
  39. }
  40. i++;
  41. }
  42. /*
  43. * if the string is nothing but blanks,
  44. * then terminate it
  45. */
  46. if (j < 0 ) {
  47. str[0] = '\0';
  48. return 0;
  49. }
  50.  
  51. /*
  52. * if there is a gap, just insert '\n' before terminating the string
  53. * otherwise, the string is already free of tail blanks
  54. */
  55.  
  56. if (i > j + 1) {
  57. str[j+1] = '\n';
  58. str[j+2] = '\0';
  59. }
  60. return j+1;
  61. }
  62.  
  63. int
  64. main()
  65. {
  66. int len;
  67. char line[MAXLINE];
  68. /* current line length */
  69. /* maximum length seen so far */
  70. while ((len = get_line(line, MAXLINE)) > 0) {
  71. chomp(line);
  72. printf("%s",line);
  73. }
  74. return (0);
  75. }
Advertisement
Add Comment
Please, Sign In to add comment