Quote as argument to macro 
Author Message
 Quote as argument to macro

I'm trying to write some code that replaces an escape sequence in a
string with the appropriate character, e.g. that would replace "\\n"
with "\n", or that would change a file consisting of a backslash and the
letter 'n' to the newline character.  To make life easier on myself,
I've written a macro to quickly test for a given escape sequence, and
it's my first attempt to use the token pasting operator ##.

Here's the smallest code that should compile that demonstrates my
problem:

#include <stdio.h>

#define TRY_ESCAPE(x) if (c == '##x##') *currentPtr++= '\##x##'

int main(void) {
    int c=0;
    char escapedString[512]={0};
    char* currentPtr=escapedString;
    int isEscaped=0;
    while (c != EOF || currentPtr >= &escapedString[511]) {
      c=getchar();
      if (isEscaped) {
        if (c==EOF) fatalError("Unexpected \\");
        else TRY_ESCAPE(");
        else TRY_ESCAPE(');
        else TRY_ESCAPE(\);
        else TRY_ESCAPE(a);
        else TRY_ESCAPE(b);
        else TRY_ESCAPE(f);
        else TRY_ESCAPE(n);
        else TRY_ESCAPE(r);
        else TRY_ESCAPE(t);
        else TRY_ESCAPE(v);
        else {
          char error[32];
          sprintf(error, "Unknown escape sequence \\%c", c);
          fatalError(error);
        }
      }
      else if (c=='\\') {
         isEscaped=YES;
      }
      else if (c != EOF) *currentPtr++=c;
   }
   return 0;

Quote:
}

This code produces the following errors:

test.c:26:49: missing terminating " character
test.c:14:35: possible start of unterminated string literal
test.c:36:1: unterminated argument list invoking macro "TRY_ESCAPE"

I also recognize that even if I solve this prolem, TRY_ESCAPE(") would
produce the code

if (c == '"') *currentPtr++= '\"'

which doesn't correctly escape the first quote.

How can I accomplish what I want?  Thanks for any help.

-Peter



Sun, 05 Dec 2004 02:12:39 GMT  
 
 [ 1 post ] 

 Relevant Pages 

1. Need Portable way to quote an argument in a macro

2. Preprocessor macro to quote its argument

3. embedded quotes in arguments to functions

4. C command-line arguments & quotes

5. aliasing single quotes in macros

6. aliasing quotes in macros?

7. define macros (with quotes and spaces) in VC6 ide's project setting page

8. macro replacement in quoted strings

9. macro replacement in quoted strings

10. Parsing quotes and double quotes

11. wrong number of arguments to a macro?!

12. variable argument macros

 

 
Powered by phpBB® Forum Software