-1

What would you use to check for escape sequenced values? I have two inputs arg1 and arg2. If you enter ab\t xyz into the arguments. And then if you were to type in "ab\t" into the input you would get "xyz" as output. I hope this makes sense and im really stuck at the escape character handling. Currently the code works for all except for when there are escape chars or if one argument is longer than the other.

it is a c code we wrote on our own the plan is to make a custom tr() function
void tr_str(char s[], char news[]){
    int c;
    size_t k =0;
        while ((c = getchar()) != EOF)
        {
            for(k=0; k < strlen(s);k++)
            {                   
                if(c == s[k])
                {
                    c = news[k];
                }
            }
            putchar(c);
        }
    }
TheUnknown
  • 53
  • 2
  • 10

1 Answers1

0

EDIT:

I have interpreted escape chars in two ways. First the tab character is in the array s[], and secondly I trap the \ char in the escape sequence of \t and use a second pair of arrays to translate the escape sequence.

#include <stdio.h>
#include <string.h>

int main(void) { 
    char s[]="abcd\t";
    char news[]="ABCD!";
    char e[]="t";
    char newe[]="!";
    int c, k, esc = 0;
    while ((c = getchar()) != EOF) {
        if (esc) {
            for (k=strlen(e)-1; k>=0; k--) {
                if (c == e[k]) {
                    c = newe[k];
                    break;
                }
            }
            putchar(c);
            esc = 0;
        }
        else if (c == '\\') {
            esc = 1;
        } 
        else {
            for (k=strlen(s)-1; k>=0; k--) {
                if (c == s[k]) {
                    c = news[k];
                    break;
                }
            }
            putchar(c);
        }
    }
    return 0;
}

Program input (the spaces result from the tab key)

a\tz      d

Program output:

A!z!D
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • i suspect the OP problem is trying to enter the \t character into the args when running it from the command line- ie tr "abcd\t" "xyxpq", he seems to be saying that he ends up with \ and t – pm100 Feb 05 '15 at 23:43
  • @pm100 answer improved, a similar way can be used if the input comes from a program argument, but OP uses `getchar()`. – Weather Vane Feb 06 '15 at 00:14