Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

c - A funny thing with sprintf

I'm so confused with sprintf that a funny problem with different platfrom. Code :

int main () 
{
    char sql[1024];
    uint32_t app_id = 32;
    uint64_t task_id = 64;
    sprintf(sql, "%u, %u", task_id, app_id);
    printf ("%s
", sql);
    return 0;
}

The result in console (MSVC2010 debug/release): 64, 0

But the same code in console(CentOS64 gcc4.4.6): 64, 32

Any guy will help me, tks!

-------------updated--------------------------

Thanks guys. I have read this article: sprintf for unsigned _int64

Actually, PRIu64 in "inttypes.h" defined: I64uwhich is not supported on windows. So I can write like this:

sprintf(sql, "%I64u, %I32u", task_id, app_id);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use %llu format string for task_id in sprintf()as follows:

sprintf(sql, "%llu, %u", task_id, app_id);
//             ^
//            for: long long unsigned int

Edit: As @Simonc suggested its better to use: PRIu32 and PRIu64 macros defined in <inttypes.h> (as you have Linux tag) do like:

sprintf(sql, "%"PRIu64", %"PRIu32"", task_id, app_id);
//               ^           ^
//       for:   uint64_t    uint32_t  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...