Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Exercise 1-19.
- * Write a function reverse(s) that reverses the character string s.
- * Use it to write a program that reverses its input a line at a time.
- */
- #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;
- }
- void reverse(char *str) {
- int i, len;
- char c;
- i = 0;
- /* calculate the length of the string */
- while (str[i] != '\0' && str[i] != '\n') {
- ++i;
- }
- len = i;
- /* reverse the string */
- for (i = 0; i < len/2; i++) {
- c = str[i];
- str[i] = str[len - 1 - i];
- str[len - 1 - i] = c;
- }
- }
- int
- main()
- {
- int len;
- char line[MAXLINE];
- /* current line length */
- /* maximum length seen so far */
- while ((len = get_line(line, MAXLINE)) > 0) {
- reverse(line);
- printf("%s",line);
- }
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment