Skip to content

Instantly share code, notes, and snippets.

@Learath2
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save Learath2/8fb2fb64ff7c324672f2 to your computer and use it in GitHub Desktop.

Select an option

Save Learath2/8fb2fb64ff7c324672f2 to your computer and use it in GitHub Desktop.
K&R2 Exercise 3-2
/*K&R2 Exercise 3-2 "escape"*/
#include <stdio.h>
#define MAX_LINE 1024
int getl(char[], int);
void escape(char[], char[]);
void unescape(char[], char[]);
int main()
{
char s[MAX_LINE];
char t[MAX_LINE];
while(getl(t, MAX_LINE)){
escape(s, t);
printf("Escaped: %s\n", s);
unescape(t, s);
printf("UnEscaped: %s", t);
}
}
int getl(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;
s[i] = '\0';
return i;
}
void escape(char s[], char t[])
{
int i, j;
for(i = 0, j = 0; t[i] != '\0'; i++){
if(t[i] == '\n'){
s[j++] = '\\';
s[j++] = 'n';
}
else if(t[i] == '\t'){
s[j++] = '\\';
s[j++] = 't';
}
else
s[j++] = t[i];
}
}
void unescape(char s[], char t[])
{
int i, j;
for(i = 0, j = 0; t[i] != '\0'; i++) {
if(t[i] == '\\' && t[i+1] == 'n') {
s[j++] = '\n';
i++;
}
else if(t[i] == '\\' && t[i+1] == 't') {
s[j++] = '\t';
i++;
}
else
s[j++] = t[i];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment