summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdam Carpenter <53hornet@gmail.com>2019-05-14 15:41:19 -0400
committerAdam Carpenter <53hornet@gmail.com>2019-05-14 15:41:19 -0400
commit3ce6dbf9b9958b44acb1e545fe4fead4aefaf90a (patch)
tree1ebb8198f93600df0b16d1411f041c7aa853e804
parent3c03bde0755595a104ceb2430e6842fd46de4e74 (diff)
downloadlearning-c-3ce6dbf9b9958b44acb1e545fe4fead4aefaf90a.tar.xz
learning-c-3ce6dbf9b9958b44acb1e545fe4fead4aefaf90a.zip
Started reverse
-rw-r--r--no_trailers.c2
-rw-r--r--reverse.c68
2 files changed, 69 insertions, 1 deletions
diff --git a/no_trailers.c b/no_trailers.c
index e600e35..80dbc0f 100644
--- a/no_trailers.c
+++ b/no_trailers.c
@@ -8,7 +8,7 @@ void copy(char to[], char from[]);
/*
* MAIN
- * Prints longest line in STDIN.
+ * Removes all trailing whitespace and blank lines from STDIN.
*/
int main() {
int len; // current line length
diff --git a/reverse.c b/reverse.c
new file mode 100644
index 0000000..0681560
--- /dev/null
+++ b/reverse.c
@@ -0,0 +1,68 @@
+#include<stdio.h>
+
+#define MAXLENGTH 1000
+
+// Prototypes
+int get_line(char line[], int maxlength);
+void line_copy(char to[], char from[]);
+void reverse_copy(char to[], char from[]);
+
+/*
+ * MAIN
+ * Reverse all lines on STDIN.
+ */
+int main() {
+ int len; // current line length
+ char line[MAXLENGTH]; // current input line
+ char reversed_line[MAXLENGTH]; // current reversed line
+
+ while ((len = get_line(line, MAXLENGTH)) > 0) {
+ reverse_copy(line, reversed_line, len);
+ printf("%s\n", reversed_line);
+ }
+ return 0;
+}
+
+/*
+ * GET_LINE
+ * Read STDIN into LINE up to MAXLENGTH.
+ * Returns the length of LINE.
+ */
+int get_line(char line[], int maxlength) {
+ int c, i;
+
+ for (i = 0; i < maxlength - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
+ line[i] = c;
+ if (c == '\n') {
+ line[i] = c;
+ ++i;
+ }
+ line[i] = '\0';
+ return i;
+}
+
+/*
+ * LINE_COPY
+ * Copy FROM into TO; assume TO is big enough.
+ */
+void line_copy(char to[], char from[]) {
+ int i;
+
+ i = 0;
+ while ((to[i] = from[i]) != '\0')
+ ++i;
+}
+
+/*
+ * REVERSE_COPY
+ * Copy FROM into TO (of length LENGTH) in reverse order; assume TO is big
+ * enough.
+ */
+void reverse_copy(char to[], char from[], int length) {
+ int i;
+
+ i = 0;
+ while ((to[i] = from[i]) != '\0')
+ ++i;
+}
+