2016-12-24 76 views
-5

出于某种原因,我无法写入从scanf_s我在Visual Studio 2013中使用的ch字符类型我尝试了间距“%c”两种方式“%c”,并尝试scanf和scanf_s。我搞不清楚了。字符类型不接受输入

// Alphabetic Pyramid Program - The Egyptians must have used C! 
#include <stdio.h> 

int main(void) 
{ 
    char ch; 

    printf("Enter the letter that will be the foundations of your Aphabetic Pyramid:\n"); // User is promted to enter a letter 
    scanf_s(" %c", &ch); // User inputs Foundational_letter 
    printf("The code for %c is %d!\n", ch, ch); 

    getchar(); 
    getchar(); 

    return 0; 
} 
+1

欢迎来到Stack Overflow。请花些时间阅读[The Tour](http://stackoverflow.com/tour),并参阅[帮助中心](http://stackoverflow.com/help/asking)中的资料,了解您可以在这里问。 –

+2

请记住:C和C++不是同一种语言。只标记一个。另外,对于'scanf_s',我相信你需要提供缓冲区的大小:'scanf_s(“%c”,&ch,1);' –

+0

“我无法从scan_f写入ch char类型。请更具体一些。有错误吗?如果行为不正确,请提供输入,预期结果和实际结果。 – kaylum

回答

4

scanf_s预计为%c符两个参数:接收地址和大小,这是1:

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

通过设计,scanf函数的所有安全版本(那些_s结尾)需要一些参数,指定在类型为string(%s)和char(%c)时为接收输入保留了多少缓冲区空间。即对于%s,您将指定缓冲区地址及其保留大小。

如果您不应用这些规则,则预计未定义的行为。

+0

[“读取非空终止字符串的多个字符时,整数用作宽度规格和缓冲区大小。”](https://msdn.microsoft.com/zh-cn/library/w40768et.aspx# ANCHOR_2) – Stargateur