首先,SCANF为下一个scanfs获得其他Chrachter
我正在在C中制作一个简单的计算器,我希望该程序显示消息“输入操作员!”当用户输入不是操作员的东西时,请输入,空间或选项卡。但是,如果用户输入类似123的数字,则显示3次消息,而不是一次。我该如何解决?
char op;
printf("please choose an operator (+,-,*,/): ");
while (op!='+' && op!='*' &&op!='-' &&op!='/' )
{
if (op!='\n'&& op!= '\t'&& op!=' ')
printf ("Enter an operator!\n");
scanf ("%c",&op);
}
I'm making a simple calculator in C and I want the program to show the message "Enter an operator!" when the user enters something that isn't an operator, enter, space or tab. but if the user enters a number like 123 the message is shown 3 times instead of once. how can I fix this?
char op;
printf("please choose an operator (+,-,*,/): ");
while (op!='+' && op!='*' &&op!='-' &&op!='/' )
{
if (op!='\n'&& op!= '\t'&& op!=' ')
printf ("Enter an operator!\n");
scanf ("%c",&op);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以使用扫描集
%1 [+ - /*]
将在一组运算符中扫描一个字符。如果字符不在集合中,
scanf
将返回0
。清洁输入流,然后重试。A scan set could be used
%1[+-/*]
will scan one character in the set of operators.If the character is not in the set,
scanf
will return0
. Clean the input stream and try again.首先,使用格式字符串
“%c”
输入字符。请注意格式字符串中的领先空间。它允许跳过白空间字符,例如新行字符'\ n'
。请注意,您正在使用非初始化的变量OP在WARE循环的条件下导致行为不确定。
简化的方法可以看起来以下方式
For starters use the format string
" %c"
to enter a character. Pay attention to the leading space in the format string. It allows to skip white space characters as for example the new line character'\n'
.Pay attention to that you are using an uninitialized variable op in the condition of the while loop that results in undefined behavior.
A simplified approach can look the following way
第一件事首先。我了解到的1规则是,功能只能做1件事。
在您的情况下,
scanf(“%c”,& op)
被多次调用。在
scanf()
之间放置while()
loop和printf()
和重试。您也可以使用
do {...} while;
循环。1st thing first. 1 rule I learned is that a function only do 1 thing.
In your case,
scanf("%c", &op)
is being called multiple times.Put the
scanf()
between thewhile()
loop andprintf()
and retry.You can use a
do{...}while;
loop too.