2012-05-21 20 views
1

我目前正在为我的玩具语言编写解析器,并作为解析器的一部分,我已经写好打印函数,以及...基本上打印它的论点。对于字符串常量,它是所有打印字符串(字符*)从文件加载没有逃脱特殊序列(如 n)

printf("%s", pointer); 

所以

print("\n") 

printf("%s", ptr_to_loaded_string); 

执行(或多或少)

但是,我现在的问题是, C读取脚本文件时会转义特殊字符序列。因此,而不是“\ n”我得到“\\ n”。

我的问题是:有没有什么办法可以避免这个序列的转义,如果不是,处理它们的最好方法是什么?我目前正在考虑搜索和替换 - 用'\'替换2'\'的每个序列,但它可能有点问题(字符串长度变化,重新分配等) - 我想避免这种解决方案,除非它是绝对有必要。

编辑:哎呀,计算器逃过我的例子....

+0

是否该脚本文件包含换行符,或字符''\''后面跟着一个字符'N'? –

+0

当前脚本文件只包含1行:'print(“test \ n”)'并且导致打印'test \ n' – stollgrin

+1

正确,因为转义序列仅在_literal_字符串中被替换,即在你的C源代码中。 –

回答

2

并不是说C不会逃避你的序列 - 它只是让它们单独存在,所以你在输入流中的“\ n”被认为是两个字符('\'和'n')。

下面是一些代码,我写前处理这个:

/* 
** Public Domain by Jerry Coffin. 
** 
** Interpets a string in a manner similar to that the compiler 
** does string literals in a program. All escape sequences are 
** longer than their translated equivalant, so the string is 
** translated in place and either remains the same length or 
** becomes shorter. 
*/ 

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

char *translate(char *string) 
{ 
     char *here=string; 
     size_t len=strlen(string); 
     int num; 
     int numlen; 

     while (NULL!=(here=strchr(here,'\\'))) 
     { 
      numlen=1; 
      switch (here[1]) 
      { 
      case '\\': 
        break; 

      case 'r': 
        *here = '\r'; 
        break; 

      case 'n': 
        *here = '\n'; 
        break; 

      case 't': 
        *here = '\t'; 
        break; 

      case 'v': 
        *here = '\v'; 
        break; 

      case 'a': 
        *here = '\a'; 
        break; 

      case '0': 
      case '1': 
      case '2': 
      case '3': 
      case '4': 
      case '5': 
      case '6': 
      case '7': 
        numlen = sscanf(here,"%o",&num); 
        *here = (char)num; 
        break; 

      case 'x': 
        numlen = sscanf(here,"%x",&num); 
        *here = (char) num; 
        break; 
      } 
      num = here - string + numlen; 
      here++; 
      memmove(here,here+numlen,len-num); 
     } 
     return string; 
} 
+0

对,为什么我以前没有想过呢?现在我感到很蠢 – stollgrin

1

你不能从字符序列直接解释(例如从输入文件)C风格的特殊字符。您需要编写解析逻辑来确定序列是否包含所需的特殊字符序列并对其进行相应处理

注意:确保您也正确处理了逃逸转义字符。

0

如果您愿意使用GLib,您可以使用g_strcompress您的字符串来转换转义字符,然后打印结果。