Re: [問題] Macro 要如何擷字串

看板C_and_CPP (C/C++)作者 (pica)時間10年前 (2015/10/04 12:51), 10年前編輯推噓1(101)
留言2則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《einstein328 (pica)》之銘言: : 開發平台(Platform): (Ex: VC++, GCC, Linux, ...) : gcc : 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) : 問題(Question): : 要如何透過macro擷取字串出來. 這有點難解釋我用底下的sample code來解釋. : 餵入的資料(Input): : 預期的正確結果(Expected Output): : 底下的code, 會輸出 enum_my_int 得字串, : 想請問要如何做, 在macro的操作下, 可以把enum_ 移除. : 只留下,想要的my_int : 錯誤結果(Wrong Output): : 程式碼(Code):(請善用置底文網頁, 記得排版) : 4 typedef int my_int; : 5 typedef double my_double; : 6 : 7 typedef enum : 8 { : 9 enum_my_int, : 10 enum_my_double, : 11 } enum_type; : 12 : 13 #define macro_test_str(p) #p : 14 : 15 void main(void) : 16 { : 17 : 18 printf("%s\n", macro_test_str(enum_my_int)); : 19 : 20 } : 補充說明(Supplement): 感謝版友回覆, 其實我是想用 macro 後的字串來當作資料型態去宣告變數. 4 typedef int my_int; 5 typedef int declare_enum_my_int; 6 typedef double my_double; 7 8 typedef enum 9 { 10 enum_my_int, 11 enum_my_double, 12 } enum_type; 13 14 #define macro_test_str(p) #p+5 15 #define declare_macro_test_str(a,p) a##p 16 17 void main(void) 18 { 19 20 printf("%s\n", macro_test_str(enum_my_int)); 21 // macro_test_str(enum_my_int) a // NG 22 declare_macro_test_str(declare_, enum_my_int) a; // OK 23 24 a =3 ; 25 printf("%d \n", a); 26 } 我是想達成 line:22 這件事情, 假如我這樣處理的話, 會變得有點醜... 所以想問一下, 有沒有更好的方式可以. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.231.105.117 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1443934311.A.871.html ※ 編輯: einstein328 (61.231.105.117), 10/04/2015 12:52:55

10/04 17:59, , 1F
那你倒過來, macro 參數給型別, enum 名字用 ## 黏上去
10/04 17:59, 1F

10/04 18:00, , 2F
啊, 沒看到你 22 行就是這麼做的了...
10/04 18:00, 2F
文章代碼(AID): #1M4B1dXn (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1M4B1dXn (C_and_CPP)