Skip to content

Instantly share code, notes, and snippets.

@soyart
Created October 1, 2023 15:42
Show Gist options
  • Save soyart/11021e4deb20cb0b6a00a0d05f98e823 to your computer and use it in GitHub Desktop.
Save soyart/11021e4deb20cb0b6a00a0d05f98e823 to your computer and use it in GitHub Desktop.
K&R exercise 1-18
#include <stdio.h>
#define MAXLEN 1000
/* Avoid confilic with stdio.h */
int _getline(char line[], int limit);
int main(void) {
char line[MAXLEN];
int i, j, c, len;
while ((len = _getline(line, MAXLEN)) > 0) {
for (i = len; i > 0; --i) {
if ((c = line[i-1]) != '\0' && c != '\n' && c != '\t' && c != ' ') {
break;
}
}
for (j = 0; j < i; ++j)
printf(">%c", line[j]);
printf("\n");
}
return 0;
}
/* Safely get line within limit `lim` */
int _getline(char s[], int lim) {
int i, c;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
s[i] = c;
}
/*
If whole line was read, then last c would have been \n,
so we add it **back** here.
*/
if (c == '\n') {
s[i] = c;
++i;
}
/* Terminate s with \0 */
s[i] = '\0';
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment