0

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);
    }
  }

}
Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
omm118
  • 315
  • 3
  • 12

1 Answers1

0

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);.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • And also remove space in " %c" i.e "%C" for the above. – VDN Nov 26 '13 at 10:56
  • Thank you, this solved it. However i still need to put space before %c. – omm118 Nov 26 '13 at 10:59
  • 1
    @VDN the space in the format string is needed in this case to consume the newline character left in stdin by the previous use of scanf_s to read num at the start of the while() loop. – Nigel Harper Nov 26 '13 at 11:05