作者LPH66 (1597463007)
看板C_and_CPP
標題Re: [問題] printf type of value
時間Tue Jul 29 02:07:19 2014
: → qas612820704:其實是因為我用#define DATATYPE XXXX 07/29 01:28
: → qas612820704:然而要printf時要給format 可是我之後在用這個檔案時 07/29 01:29
: → qas612820704:可能會把 XXXX 改成 int 或是 char之類的 07/29 01:30
: → qas612820704:所以我不確定我寫一些變數他的type是什麼 07/29 01:31
: → qas612820704:只確定他的type示我define的那個DATATYPE 07/29 01:31
: → qas612820704:所以我想反向知道我的DATATYPE a是什麼 07/29 01:33
: → qas612820704:然後再給一些關於那個type的操作例如printf 07/29 01:34
: → qas612820704:就我這樣講好像就是給他一些適度的附載平衡就解掉了 07/29 01:35
: → qas612820704:那如果是這樣的話 要怎麼 overflow <(_ _)> 07/29 01:37
C 語言的話應該只能暴力解了...
還好你的情境應該只會用在 primitive type 上
如果沒有用到兩個 keyword 以上的型態 (例如 long long)
那應該可以這麼做:
#define DATATYPE XXX
/* 更多就再加 */
#define FORMAT_int "%d"
#define FORMAT_char "%c"
#define FORMAT_long "%ld"
#define FORMAT_float "%f"
/* 要多一層的原因是因為在下面使用中 DATATYPE 得讓它先展開的關係
如果直接 ## 就不會展開, 只會得到 FORMAT_DATATYPE */
#define FORMAT1(type) FORMAT_ ## type
#define FORMAT(type) FORMAT1(type)
void output(DATATYPE data)
{
/* 下面這麼寫 OK 的原因是因為
C/C++ 裡兩個或以上的常數字串並排時 (例如 "foo" "bar" 這樣)
編譯器會幫你接在一起 (上例就是等同於 "foobar") */
printf("data = " FORMAT(DATATYPE), data);
}
--
C++ 有 overloading, 編譯器可以判斷型態選擇要呼叫的函數
所以單寫 cout << data; 編譯器會知道那是什麼型態然後印出來
--
'Oh, Harry, don't you
see?' Hermione breathed. 'If she could have done
one thing to make
absolutely sure that every single person in this school
will read your interview, it was
banning it!'
---'Harry Potter and the order of the phoenix', P513
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.195.39.85
※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1406570843.A.C26.html
推 IhateOGC:Macro 神人\(^▽^)/ 07/29 02:24
→ loveme00835:<inttypes.h> 07/29 03:16
推 qas612820704:不好意思可以解釋一下這兩行嗎 07/29 09:53
→ qas612820704:#define FORMAT1(type) FORMAT_ ## type 07/29 09:53
→ qas612820704:#define FORMAT(type) FORMAT1(type) 07/29 09:53
→ qas612820704:第1行這什麼鬼=_=... 07/29 09:54
→ suhorng:## 就是接起來阿 07/29 13:44