简体   繁体   English

无法为变量的scanf_s值打印f ASCII值

[英]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. 尝试获取字符的用户输入值,然后将其显示为ASCII整数。 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. 但是,如果我手动分配的字符信let它工作正常。

#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 : 根据Microsoft的文档

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 [] . scanfwscanf不同, scanf_swscanf_s 要求[]中包含的cCsS类型或字符串控制集的所有输入参数指定缓冲区大小。 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. 注意,我没有包括真正不安全的变体,例如gets(str)scanf ("%s",str)但那些您知道并控制要消耗多少输入的变量就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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