Search code examples
cchar

Having trouble with char and scanf_s()


I just started using C and i'm having some trouble compiling. It seems that the compiler constantly has trouble with char. Notice how i have to put space before %c. Now after researching online for a bit i learned that adding , 1 after &flag pretty much solves this, but i rather solve this completely, as it should work fine like this. I'm using Visual studio 2013 btw.

#include <stdio.h>

void main()
{

  int num;
  char flag;
  while (1)
  {

    printf("Please enter your no.:");
    scanf_s("%d", &num);

    if (num > -1)
    {

      if (num < 10)
      {
        printf("Your number is 1 digit.\n");
      }

      else if (num < 100)
      {
        printf("Your number is 2 digits.\n");
      }

      else if (num < 1000)
      {
        printf("Your number is 3 digits.\n");

      }

      else if (num > 999)
      {
        printf("Your number has a lot of digits.\n");

      }
    }

    else
    {
      printf("Please input a correct value.\n");

    }

    printf("Would you like to countinue? y/n \n");
    scanf_s(" %c", &flag)
    // problem

    if (flag == 'n')
    {
      exit(0);
    }
  }

}

Solution

  • Your code is not valid, you must specify the buffer size with scanf_s(). See the documentation:

    Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or [. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.

    That is why it works if you add make the call scanf_s(" %c", &flag, 1);.