我在用 C 语言输入字符时遇到问题。我希望用户只输入 x
或 X
。如果没有,用户必须重新输入。而且,我想用一个结构来做。这是我的代码:
typedef struct chu{
char c;
};
int main(){
chu input;
char temp;
do{
printf("\nInput: ");
temp=getche();
if((temp!='x')||(temp!='X'))
printf("\nWrong input (only 'x' or 'X')");
else
input.c=temp;
}while((temp!='x')||(temp!='X'));
}
当我输入x
或X
时,我不应该再输入。
最佳答案
你的 if 条件是错误的,它应该是:
if((temp!='x') && (temp!='X'))
^ && if not both
我将 ||
替换为 &&
(因为任何一个都被接受,所以如果 temp 不等于两者,则应该打印条件错误消息 )
第二个 while 条件应该是:
while(!((temp =='x') || (temp=='X')));
^
正如你所说当我输入 x 或 X 时,我不应该再次输入 所以如果 temp
是 x
或 X
然后 (temp =='x') || (temp=='X')
== 1
并且由于 !
它给出了 while(0)
和循环中断
另外,你的结构定义应该是这样的:
typedef struct {
char c;
}chu;
我更正了您的代码,您可以找到 from here并在你的机器上试一试。
关于c - 在 C 中使用 getche 在结构中输入一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15728539/