-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[c_book] ex-1-19 reverses one line at time
- Loading branch information
Showing
2 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|
||
|