Re: [問題] printf type of value
: → 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
推
07/29 02:24, , 1F
07/29 02:24, 1F
→
07/29 03:16, , 2F
07/29 03:16, 2F
推
07/29 09:53, , 3F
07/29 09:53, 3F
→
07/29 09:53, , 4F
07/29 09:53, 4F
→
07/29 09:53, , 5F
07/29 09:53, 5F
→
07/29 09:54, , 6F
07/29 09:54, 6F
推
07/29 09:56, , 7F
07/29 09:56, 7F
→
07/29 13:44, , 8F
07/29 13:44, 8F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 4 篇):