问题是,当我输入除y
或n
之外的任何字符时,它会将此消息显示两次而不是一次显示
This program is 'Calculator'
Do you want to continue?
Type 'y' for yes or 'n' for no
invalid input
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main ()
{
//program
//first to get two numbers
//second to get choice
int x=0,y=0,n=0;
char choice;
//clrscr(); does no work in devc++
system("cls"); //you may also use system("clear");
while(x==0)
{
puts("\t\tThis program is 'Calculator'\n\n");
puts("Do you want to continue?");
puts("Type 'y' for yes or 'n' for no ");
scanf("%c",&choice);
x++;
if(choice=='y')
{
y++;
puts("if this worked then we would continue to calculate the 2 no");
}
else if(choice=='n')
exit(0);
else
{
puts("invalid input");
x=0;
}
}
getch();
}
`
答案 0 :(得分:2)
它循环两次因为输入(\ n)字符存储在缓冲区中使用scanf像这样(在%c之前添加空格)
scanf(" %c",&choice);
答案 1 :(得分:1)
这是因为在您输入y
或n
并点击后输入键后会有新的新行。
试试这个:
scanf("%c",&choice);
while(getchar()!='\n'); // Eats up the trailing newlines
答案 2 :(得分:0)
如果您输入“&#39; y&#39;以外的任何字符?或者&#39; n&#39;,控制进入:
else
{
puts("invalid input");
x=0;
}
阻止,将x重置为0,现在是循环条件:
while(x == 0)
是真的,因此它再次进入循环。
此外,您可能希望在阅读时跳过尾随换行符:
scanf(" %c", &choice );