Exercise 3.2 - escape sequences into the real characters

Question

Write a function escape(s,t) that converts characters like newline and tab into visible escape sequences like n and t as it copies the string t to s. Use a switch. Write a function for the other direction as well, converting escape sequences into the real characters.

/* Write a function escape(s,t) that converts characters like newline and tab
into visible escape sequences like \n and \t as it copies the string t to s. Use
a Switch. Write a function for the other direction as well,converting the escape
sequences into the real characters */

#include <stdio.h>
#define MAXLINE 1000
int mgetline(char line[], int maxline);
void escape(char s[], char t[]);

int main(void) {
    char s[MAXLINE], t[MAXLINE];

    mgetline(t, MAXLINE);

    escape(s, t);

    printf("%s", s);

    return 0;
}

void escape(char s[], char t[]) {
    int i, j;

    i = j = 0;

    while (t[i] != '\0') {
        switch (t[i]) {
        case '\t':
            s[j] = '\\';
            ++j;
            s[j] = 't';
            break;
        case '\n':
            s[j] = '\\';
            ++j;
            s[j] = 'n';
            break;
        default:
            s[j] = t[i];
            break;
        }
        ++i;
        ++j;
    }

    s[j] = '\0';
}

int mgetline(char s[], int lim) {
    int i, c;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF; ++i)
        s[i] = c;

    s[i] = '\0';
}

Explanation

C Program interpreters \n and \t as space characters and outputs them. Our intention is to capture the \n and \t characters and display them visibly as n or t. In order to do that we need to escape them, the escaping is done by adding \ character.

So in the program as soon as we see a \n character, in the array where we are copying to, we copy \\ character and add a n character and similarly, when we see a \t character, in the array where we are copying to, we copy \\ character and add a t character.