2012-05-21 36 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您的字符串來轉換轉義字符,然後打印結果。