Reading a character with scanf_s

巧了我就是萌 提交于 2019-11-26 07:49:28

问题


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

}

See program output


回答1:


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

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

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

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

According to msdn:

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:

char c;

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




回答2:


With scanf_s you must supply a length [1] :

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

In the case of scanf_s think of %c to be a special shortcut for %1c, which makes this more clear.

MSDNAA states [1]:

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 [...].

[1] https://msdn.microsoft.com/en-us/library/w40768et.aspx




回答3:


The documentation of scanf_s says that:

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

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

So following should work ( See live demo here )

#include <stdio.h>
int main(void)
{
  char i;
  printf("Do you want to be X's or O's?\n");
  scanf_s("%c",&i,1);
  printf("You chose %c\n", i);
}


来源:https://stackoverflow.com/questions/41199504/reading-a-character-with-scanf-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!