Format specifiers for uint8_t, uint16_t, ...?

If I have an integer variable, I can use sscanf as shown below using the% d format specifier.

 sscanf (line, "Value of integer: %d\n", &my_integer); 

Where can I find format specifiers for uint8_t , uint16_t , uint32_t and uint64_t ?

uint64_t has probably% lu.

+47
c ++ c ++ 11 scanf
Aug 09 2018-11-11T00:
source share
6 answers

They are declared in <inttypes.h> as macros: SCNd8, SCNd16, SCNd32 and SCNd64. Example (for int32_t):

 sscanf (line, "Value of integer: %" SCNd32 "\n", &my_integer); 

Their format is PRI (for printf) / SCN (for scanning), then o, u, x, X d, I for the corresponding qualifier, then nothing, LEAST, FAST, MAX, and then the size (obviously, for the maximum size). Some other examples: PRIo8, PRIuMAX, SCNoFAST16.

Edit: BTW a related question asked why this method was used. You can find answers to interesting questions.

+78
Aug 09 2018-11-11T00:
source share
β€” -

As others have said, include the <stdint.h> header, which defines format macros. However, in C ++, define __STDC_FORMAT_MACROS before turning it on. From stdint.h:

 /* The ISO C99 standard specifies that these macros must only be defined if explicitly requested. */ #if !defined __cplusplus || defined __STDC_FORMAT_MACROS 
+7
Aug 09 '11 at 8:22
source share

According to 7.19.6. Formatted I / O functions ISO / IEC 9899: TC2, there are no such format specifiers (therefore, I doubt that they exist for C ++ 2003). Although there are some # define macros in C99 inttypes.h , cinttypes and inttypes.h are not part of the current standard. Of course, integer types of fixed size are also non-standard.

In any case, I seriously recommend using streams:

 <any_type> x; f >> x; 

and do it. For example:.

 std::stringstream ss; uint32_t u; std::cin >> u; 

This has the advantage that, once in the future, changing the type of a variable does not cause a cascade of subtle errors and undefined behavior.

+2
Aug 09 '11 at 8:20
source share

In C, the header is <inttypes.h> and formats such as SCNX8, SCNd16.

The same header probably also works for C ++.

0
Aug 09 '11 at 8:12
source share

The correct format is for reading uint64_t (typedef unsigned long long int) with scanf , not sscanf , "%" SCNu64 and for printing also SCNu64 Example. in your code you read, for example, the variable my_integer, then you do scanf ("Value of integer:%" SCNu64, & my_integer); and write the same, but with printf.

0
May 08 '16 at 17:52
source share

Refer to this to use sscanf.

These data types are defined in stdint.h. Contact here for stdint.h

Shash

-one
Aug 09 '11 at 8:10
source share



All Articles