用scanf_s读取字符 [英] Reading a character with 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?\n");
scanf_s("%c", &c);
printf("You chose %c\n", 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 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屋!