0

I am getting the following error message after compiling the below code: "scanf_s: format type %c requires an argument of type 'unsigned int', but variadic argument 2 has type char."

In all the documentation I have seen %c donates data type char so I don't understand why the below is not working?

#include <stdio.h>

int main(void)
{
    char first, middle, last; /*char data type can hold 1 text value*/
    int age;

    printf("Input your three initials and your age:");
    scanf_s("%c%c%c%d", &first, &middle, &last, &age); /*data types to expect from user input, variables to assign user input to*/

    printf("\nGreetings %c.%c.%c %s %d.\n", first, middle, last, "Next year you will be", age + 1);

    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
cal17_hogo
  • 129
  • 2
  • 13
  • Use `scanf()` rather than `scanf_s()` – Barmar Nov 10 '20 at 18:46
  • thanks Barmar, but my version of visual studio is warning me against using scanf and gives a separate error message when usng scanf function. – cal17_hogo Nov 10 '20 at 18:49
  • user3121023, this fix worked, would you please be able to explain the logic? – cal17_hogo Nov 10 '20 at 18:50
  • The logic is that you're specifying buffer lengths, which is what scanf_s is all about. – Robert Harvey Nov 10 '20 at 18:51
  • I'm surprised there is no *obvious* duplicate for this ... but I' still looking ... – Adrian Mole Nov 10 '20 at 18:52
  • Yeah, my dupe was wrong, it's for the warning that got him to use `scanf_s` in the first place. – Barmar Nov 10 '20 at 18:53
  • in terms of the logic being that buffer lengths need to be specified, I thought the fact that char can only take 1 character would negate the need to do this? – cal17_hogo Nov 10 '20 at 18:53
  • 2
    char pointers should have an extra argument after them telling how many bytes to store. Also, use `#define _CRT_SECURE_NO_WARNINGS` to use scanf with Visual Studio – Nasrat Takoor Nov 10 '20 at 18:54
  • @user3121023 Why is that relevant? – Robert Harvey Nov 10 '20 at 18:55
  • 1
    @cal17_hogo but you're not passing a char, you're passing a char pointer, the compiler can't tell if it's a pointer to just 1 char, or the start of a string – Nasrat Takoor Nov 10 '20 at 18:55
  • @cal17_hogo so you might think, but the function use is as defined by MS [here](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/scanf-s-scanf-s-l-wscanf-s-wscanf-s-l?view=msvc-160) – Weather Vane Nov 10 '20 at 18:59
  • 1
    Microsoft's `scanf_s` is **not** a direct replacement for `scanf`, and the call is missing one argument for each `%c`, which the compiler warns you about. *"Unlike `scanf` ... `scanf_s` ... requires the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable."* – Weather Vane Nov 10 '20 at 19:30

0 Answers0