Skip to content

Commit

Permalink
[c_book] ex-1-19 reverses one line at time
Browse files Browse the repository at this point in the history
  • Loading branch information
ooddaa committed Apr 14, 2024
1 parent 60a4003 commit 8bc1d76
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
2 changes: 2 additions & 0 deletions c_book/1-ch/data/ex-1-19
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
this will be messed up
siht daer ot elba eb dlouhs uoy
62 changes: 62 additions & 0 deletions c_book/1-ch/exercises/ex-1-19.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#include<stdio.h>
#define MAX 1000

/*
* Reverses lines one line at a time.
*
* Prints results to stdout.
* */

int getnextline(char[], int);
void reverse(char[], int);

int getnextline(char s[], int limit)
{
int i, c;

for (i = 0; i < limit - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
s[i] = c;
}

if (c == '\n') {
s[i] = '\n';
++i;
}

s[i] = '\0';

reverse(s, i);
return i;
}

// removes trailing ' ' and \t
void reverse(char s[], int len)
{
int h, left, right;
left = 0;
right = len - 2;

while (right > left) {
h = s[left];
s[left] = s[right];
s[right] = h;
++left;
--right;
}
}


int main(void)
{
int len;
char s[MAX];
// while we have a line
while (getnextline(s, MAX) != 0) {
printf("%s", s);
}


return 0;
}


0 comments on commit 8bc1d76

Please sign in to comment.