2016-12-16 1 views
1
내 프로그램이 하나의 이스케이프 문자

은 "이스케이프 문자"

char foo(char a, char b){ 
    ... // <---how to write this part? 
} 

expectd: foo('\\','n')->'\n' 

내가 할 수있는 두 개의 인접한 문자를 (첫 번째 백 슬래시이고 두 번째는 어떤이다) 텍스트 파일을 읽고 변환됩니다

이런 Python3에 상응하는 코드를 작성 :

" 목록, ', ?, \, a, b 01에서 정합 적으로 허용 가능한 이탈 문자
tmp = bytearray([ord('\\'), ord(Char)]) 
Char == tmp.decode('utf-8') # utf-8 is just python default codec, not related to the question 
+3

C++에는 이스케이프 코드를 아는 라이브러리 기능이 없습니다. 아주 간단한 조회 기능을 작성해야합니다. –

+2

당신은 이것을 과장 생각할 수 있습니다. Sam이 지적한 것처럼 (a == '\\'&& b == 'n') return '\ n'; 그러나 그것이 아닌 경우는 어떨까요? – Jeff

+3

예를 들어 'a'는''X''이고'b'는''Y''입니까? 'foo ('X', 'Y') -> ???'. –

답변

2

검색 23,, n, v, f,

char ab_to_escape(char a, char b) { 
    if (a == `\\`) { 
    static const char *escapev = "\"\'\?\\abtnvfr"; 
    static const char *escapec = "\"\'\?\\\a\b\t\n\v\f\r"; 
    char *p = strchr(escapev, b); 
    if (p == NULL || *p == '\0') { 
     return b; // TBD this condition, invalid escape character found. 
     // Perhaps it begins an octal (0-7) or hexadecimal (x or X) escape sequence? 
     // \0 or \x42 etc. 
    } 
    return escapec[p - escapev]; 
    } 
    return a;// TBD this condition 
} 

r 내가 OP는 \\ 후 더 이상의 문자 많은있는 모든 이스케이프 시퀀스를 처리 할 수 ​​있지만 다른 기능을 필요로 생각합니다.

int Decode_Escape(char *dest, const char *src) { 
    int ch; 
    do { 
    ch = *src++; 
    if (src == '\\') { 
     if (simple_escape) Handle_Simple_Escape();   \\ \n \t ... 
     else if (octal_escape) Handle_Octal_Escape();   \\ \0 \123 
     else if (hex_escape) Handle_Hex_Escape();    \\ \x2 \XAb 
     else if (universal_escape) Handle_Universal_Escape(); \\ \uABCD \U12345678 
     else { Error(); return 1; } 
    } else { 
     *dest++ = ch; 
    } 
    } while (ch); 
    return 0; 
}