Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 304
Kiril Kirov Avatar asked Oct 17 '12 14:10

Kiril Kirov


People also ask

How do I print TC size?

We should use “%zu” to print the variables of size_t length. We can use “%d” also to print size_t variables, it will not show any error. The correct way to print size_t variables is use of “%zu”.

What is the format specifier used in scanf to read a single character from the standard input?

Format Specifier d – decimal integers. f – floating-point numbers. c – a single character.

What should I use instead of Scanf?

The most common ways of reading input are: using fgets with a fixed size, which is what is usually suggested, and. using fgetc , which may be useful if you're only reading a single char .


1 Answers

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);
like image 148
Steve-o Avatar answered Oct 15 '22 09:10

Steve-o