Last active
August 29, 2015 14:05
-
-
Save Learath2/8fb2fb64ff7c324672f2 to your computer and use it in GitHub Desktop.
K&R2 Exercise 3-2
This file contains hidden or 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
| /*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