Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C语言中不需要的双重重复_C_Loops_Do While_Repeat - Fatal编程技术网

C语言中不需要的双重重复

C语言中不需要的双重重复,c,loops,do-while,repeat,C,Loops,Do While,Repeat,假设我正在编写这段代码: char c; // c from choise. do{ printf("Please choose one of the following operators:\n"); printf("+ for Addition\n- for Subtraction\n* for Multiplication\n/ for Division\n"); printf("= for Assignment and\nE to check if two va

假设我正在编写这段代码:

char c; // c from choise.
do{
    printf("Please choose one of the following operators:\n"); 
    printf("+ for Addition\n- for Subtraction\n* for Multiplication\n/ for Division\n");
    printf("= for Assignment and\nE to check if two variables have the same type and value.\n");
    scanf("%c", &c);
}while(c!='+' && c!='-' && c!='*' && c!='/' && c!='=' && c!='E');
主要的问题是,当用户插入数字或字母时,除了上面的操作符之外的所有内容,printf中的每条消息都会在屏幕上出现两次

例如,如果c='A'我们有:

Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
A //wrong answer, the loop continues...
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
//here the program awaits the new value of c.
但是,如果c='-'或c='+'等,我们当然有

Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
= for Assignment and
E to check if two variables have the same type and value.
- // or +
//the program goes to the next line.

当我试图在while或for循环中转换do_while循环时也发生了同样的情况。

在用户键入错误字符后,stdin缓冲区中仍然(至少)有一个换行符

@haccks的评论是解决问题的一种方法。
另一种方法是在scanf之后进行一个短循环,该循环调用getchar,直到收到EOF为止。

%c
之前添加一个空格:
scanf(“%c”,&c)。这是因为以前输入的换行符可能存储在
c

如果您不想重复输入缓冲区,也可以在
scanf()
之后使用
getchar()
清除输入缓冲区。。。把指纹从循环中移开!试试这个
scanf(“%c”和&c)@haccks成功了!非常感谢你!你能解释一下原因吗?括号内的空间对我来说是个谜!所以我详细解释了很多次。如果你在这里搜索,你会很容易找到它。顺便说一句,
scanf
%c
前面的空格可以跳过任意数量的空白字符。在这种情况下,它将跳过先前的
scanf
@pmg留下的
\n
,我希望在循环中使用3个printf,以提醒用户什么是允许的,什么是不允许的。此外,这也是我使用while循环的原因。“…直到收到EOF。”嗯,在收到
'\n'
EOF
之前,您可能需要。