khalfella

ansi_c_pg31_ch01_ex19.c

Sep 26th, 2014
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. /*
  2. * Exercise 1-19.
  3. * Write a function reverse(s) that reverses the character string s.
  4. * Use it to write a program that reverses its input a line at a time.
  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. void reverse(char *str) {
  24. int i, len;
  25. char c;
  26.  
  27. i = 0;
  28.  
  29. /* calculate the length of the string */
  30. while (str[i] != '\0' && str[i] != '\n') {
  31. ++i;
  32. }
  33.  
  34. len = i;
  35. /* reverse the string */
  36. for (i = 0; i < len/2; i++) {
  37. c = str[i];
  38. str[i] = str[len - 1 - i];
  39. str[len - 1 - i] = c;
  40. }
  41. }
  42.  
  43. int
  44. main()
  45. {
  46. int len;
  47. char line[MAXLINE];
  48. /* current line length */
  49. /* maximum length seen so far */
  50. while ((len = get_line(line, MAXLINE)) > 0) {
  51. reverse(line);
  52. printf("%s",line);
  53. }
  54. return (0);
  55. }
Advertisement
Add Comment
Please, Sign In to add comment