使用 scanf_s 读取字符 [英] Reading a character with scanf_s

查看:37
本文介绍了使用 scanf_s 读取字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在玩弄 C 并遇到了这个小问题.正如你从我的输出中看到的,我得到了 '╠' 这个字符.

I was just messing around with C and ran into this small problem. As you can see from my output I getting '╠' this character.

#include <stdio.h>

int main(void)
{
    char c;

    printf("Do you want to be X's or O's?
");
    scanf_s("%c", &c);
    printf("You chose %c
", c);

}

参见程序输出

推荐答案

您滥用了 scanf_s().Microsoft 编译器可能会警告您使用他们的安全扩展(又名 c11 附件 k).但是,如果您这样做,请务必小心.scanf_s() 不是 scanf() 的直接替代品.

You are misusing scanf_s(). Microsoft compilers may warn you to use their secure extensions (aka c11 annex k). But, be careful if you do so. scanf_s() is not a direct replacement for scanf().

在这种情况下,您必须将输出缓冲区的大小作为额外参数传递.

In this case you have to pass the size of the output buffer as an extra argument.

char c;
 
scanf_s("%c", &c, 1);

必须将 1 作为单个字符的大小可能看起来有点迂腐.那是因为 %c 可以读取任意数量的字符.%c 只是 %1c(单个字符)的别名.

Having to put a 1 as the size of a single character may seem a bit pedantic. That's because %c can read any number of character. %c is just an alias for %1c (a single character).

通过了解缓冲区大小 scanf_s() 旨在防止缓冲区溢出(安全风险).

By knowing the buffer size scanf_s() is designed to prevent buffer overflow (a security risk).

虽然,这些功能到底有多大帮助是值得商榷的.请参阅:附件 K 的现场经验.

Although, how much these functions really help is debatable. See: Field Experience With Annex K.

根据msdn:

与 scanf 和 wscanf 不同,scanf_s 和 wscanf_s 需要缓冲区大小为 c、C、s、S 或字符串类型的所有输入参数指定包含在 [] 中的控制集.以字符为单位的缓冲区大小是作为紧跟在指向的指针之后的附加参数传递缓冲区或变量.

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.

在字符的情况下,单个字符可能读作如下:

In the case of characters, a single character may be read as follows:

字符 c;

scanf_s(%c", &c, 1);

scanf_s("%c", &c, 1);

这篇关于使用 scanf_s 读取字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆