比较C中用户输入的字符 [英] Comparing user-inputted characters in C
问题描述
以下代码段来自C程序。
The following code snippets are from a C program.
用户输入Y或N。
char *answer = '\0';
scanf (" %c", answer);
if (*answer == ('Y' || 'y'))
// do work
我不知道为什么 if
语句的计算结果不正确。
I can't figure out why this if
statement doesn't evaluate to true.
我用 printf
检查了y或n输入,它在那里,所以我知道我正在得到用户输入。另外,当我将if语句的条件替换为1(使它成为真)时,它的计算结果正确。
I checked for the y or n input with a printf
and it is there, so I know I'm getting the user input. Also when I replace the the condition of the if statement with 1 (making it true), it evaluates properly.
推荐答案
两个问题:
指针 answer
是 null
指针,并且您试图在 scanf
中取消引用它,这会导致未定义行为。
The pointer answer
is a null
pointer and you are trying to dereference it in scanf
, this leads to undefined behavior.
此处不需要 char
指针。您可以将 char
变量用作:
You don't need a char
pointer here. You can just use a char
variable as:
char answer;
scanf(" %c",&answer);
接下来看读取的字符是否为'y'
或'Y'
,您应该这样做:
Next to see if the read character is 'y'
or 'Y'
you should do:
if( answer == 'y' || answer == 'Y') {
// user entered y or Y.
}
如果您真的需要使用char指针,则可以执行以下操作:
If you really need to use a char pointer you can do something like:
char var;
char *answer = &var; // make answer point to char variable var.
scanf (" %c", answer);
if( *answer == 'y' || *answer == 'Y') {
这篇关于比较C中用户输入的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!