7

I am trying to use scanf() for reading an unsigned char value with %hhu, but the compiler returned me:

error: unknown conversion type character 'h' in format
 [-Werror=format]| // line 3 error: too many arguments for format
 [-Werror=format-extra-args]| // line 3 

With this following code:

printf("Enter a number: ");
unsigned char nb;
scanf("%hhu", &nb); // line 3
printf("Number: %u\n", nb);
return (nb);
perror
  • 7,071
  • 16
  • 58
  • 85
  • 1
    You are using codeblocks or some other compiler that doesn't respect the `h` format type modifier. Just change everything to `%u` and use `unsigned int`. If you need to read a `byte` use `char`. – David C. Rankin Apr 10 '16 at 15:51
  • Try adding `#define __USE_MINGW_ANSI_STDIO 1` at the top of the file or add `-D__USE_MINGW_ANSI_STDIO=1` to your preprocessor (or compiler) flags. You seem to be using a MinGW compiler, based on the diagnostic output you've provided. See [this related topic](http://stackoverflow.com/q/10678124/539810) also. –  Apr 10 '16 at 15:53
  • Add -std=c99 to the compiler options? Just guessing. – n. m. could be an AI Apr 10 '16 at 15:58
  • @DavidC.Rankin Code::Blocks is an IDE, not a compiler. It (IIRC) uses GCC as the compiler. – Spikatrix Apr 10 '16 at 16:00
  • You are 100% correct. IIRC it is one of the compilers code blocks generally works with (mingw gcc) that doesn't respect the `h` type modifier for `scanf` - my bad. – David C. Rankin Apr 10 '16 at 16:01
  • I already added -std=c99, @ChronoKitsune it doesn't work –  Apr 10 '16 at 16:01
  • Oh right, C::B is the problem.. thank's I'm gonna use an unsigned int @DavidC.Rankin –  Apr 10 '16 at 16:04
  • 3
    As a general note, unless you need to read a *byte*, then use the native types `int` or `unsigned` in your code. It will be faster because the compiler is not required to make a type-conversion from `int` to `char`, etc. If you need to limit your read to a byte use `%c` for char. The length modifiers `h` are nice, but are not implemented by all compilers. I've been bitten by this before. – David C. Rankin Apr 10 '16 at 16:13

1 Answers1

1

A discussion on this issue can be found here. This is specific to MinGW.
From this comment in the discussion the issue is identified as:

This is most likely related to bug https://sourceforge.net/p/mingw-w64/bugs/652/ in that the include order and compiler driver actually screws things up with respect to C standard output and format specifiers.

And is proposed solution is:

to always define __USE_MINGW_ANSI_STDIO so that the newer ansi format specifiers can be used and to ensure that long double (at least) is not passed between MSVC compiled and gcc compiled code.

P.W
  • 26,289
  • 6
  • 39
  • 76