简体   繁体   中英

Can't printf ASCII value for scanf_s value of variable

Trying to get the user-input value for a character, then display that as the ASCII integer number. It doesn't want to do it--as I keep getting a blank output. However, if I manually assign a character letter to let it works fine.

#include "stdafx.h"
#include <stdio.h>
#define eps 8.85e-12

int main() {

   int x = 1, y = 2, z;
   float p = 2.5, q = 4.8;
   double a = 2.5e-9, b;
   char let;

   z = 2 * y;
   printf(" x/(y+z) = %.1f \n", (float)x/(y + z));

   printf(" Get an alphabet ");
   scanf_s("%c", &let);
   printf("ASCII value of the alphabet is %d\n", let);

   printf("Insert value of b :");
   scanf_s("%lf", &b);
   printf("value of eps/(a*b)= %8.2e\n", eps / (a*b));

  return 0;
}

As per Microsoft's 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 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.

So what you need is:

scanf_s("%c", &let, sizeof(let));

although, as with most of these safe functions, they're no safer than the "unsafe" ones if you know what you're doing.

Note I'm not including the truly unsafe variants like gets(str) or scanf ("%s",str) but those where you know and control how much input you'll consume are just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM