0

I recently overheard my professor talking about being able to do something like that. I cannot find a single method that sounds like it would do that. So my question stands. In the standard getchar while loop, how would one take a peek at the next char. In this loop I pass in some arrays and have the loop switch characters from array s' chars to array news' chars for the string which is put in through command line.

anyways the code does what it is intended to do for most cases except it also has to consider "/t" etc characters as a single character not two. I was thinking of checking if(c == '\') and then checking whether the next char would be a r, t, n, etc.

TL:DR question is how do I make this loop find escape sequenced characters and consider them as one char instead of two? Thank you very much.

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

1

You peek at the next char by reading it, and then calling ungetc().

int c;
while ((c = getchar()) != EOF) {
    if (c == 'x') {
        ungetc(c, stdin);
        break;
    }
    ...
}

However, when you are processing escape sequences, you just need to getchar() twice.

while ((c = getchar()) != EOF) {
    if (c == '\\') {
        c = getchar();
        switch (c) {
        case EOF: ...
        case 'n': ...
        case 't': ...
        }
    }
    ...
}
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • Awesome. Is there a way to combine that with what I still have? Currently the program does a little of both but mostly there are no escape chars. usually the user will enter (a,b,d,e) then (w,x,y,z) then a string the program will replace the first sequence with the second sequence banana = xwnwnw problems come when users enter (\,n,\,\,\,b) (x,y,z) and then they say '\n''\\''\b' – TheUnknown Feb 08 '15 at 05:01
  • It sounds like you're on track to solving this one yourself, so I don't know what to say here. – Dietrich Epp Feb 08 '15 at 05:03