当我输入a
时,输出为not a
。条件是真的那么为什么输出not a
?当我使用getchar
而不是scanf_s
时,它工作正常。有什么问题?为什么scanf_s函数没有正确输入?
char op;
scanf_s("%c", &op);
if (op == 'a') {
printf("the character is a");
}
else {
printf("not a");
}
当我输入a
时,输出为not a
。条件是真的那么为什么输出not a
?当我使用getchar
而不是scanf_s
时,它工作正常。有什么问题?为什么scanf_s函数没有正确输入?
char op;
scanf_s("%c", &op);
if (op == 'a') {
printf("the character is a");
}
else {
printf("not a");
}
尝试scanf()
而不是scanf_s()
。
VS将使用'的scanf时发出一个警告(也许错误)()'。这很烦人。 –
@Cool盖伊http://stackoverflow.com/a/23487039/2410359安静警告 – chux
说明符%c
(两个这样的例外%s
,%[
)需要大小 -
scanf_s("%c", &op, 1); // 1 to read single character
第三参数应该是sizeof
类型第三参数。 scanf_s
仅保证可供如果__STDC_LIB_EXT1__
由实现所定义,并且如果用户包括<stdio.h>
之前定义__STDC_WANT_LIB_EXT1__
为整数常数1
。
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
int main()
{
char op;
scanf_s("%c", &op, sizeof(op));
if (op == 'a')
printf("the character is a");
else
printf("not a");
return 0;
}
您正在使用什么编译器? –
我不知道。只要运行它的Visual Studio 2013 –
尝试'scanf_s( “%C”,&OP,1);' – BLUEPIXY