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
546 views
in Technique[技术] by (71.8m points)

c - Correct way to use scanf / printf (and family) with fixed size types?

Reading this SO question, I started wondering - what is the correct way to use scanf/printf (and family) with fixed size types?

For example, if I have short int or int, I'd use %hd and %d respectively - fine.

But what if I have int16_t? short int may be different from int16_t, it's platform dependent. The same for any other fixed-size (integral) types?


NOTE: As it looks like I received some down-votes, because I "didn't try to google this", it looks like I need to explain: I didn't see similar question here, that's why I posted it. Most of the questions in SO could have been answered using Google, instead of asking here. That would make StackOverflow not the place, that it actually is now.

And NO, I didn't do this for reputation - I already hit the daily reputation cap today (having 24 up votes before posting this question).

My point is - I don't think this deserves down-votes.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The correct way is to use inttypes.h which defines standard macros for printf family and the scanf family, e.g.

printf ("%" PRId16, short_int);
scanf ("%" SCNd16, &short_int);

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

...