Reputation: 99
The problem is that when i type any character except for y
or n
it display this message two times instead to one)
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();
}
`
Upvotes: 0
Views: 107
Reputation: 22831
That is because of the trailing new line after you enter y
or n
and hit enter key.
Try this out:
scanf("%c",&choice);
while(getchar()!='\n'); // Eats up the trailing newlines
Upvotes: 1
Reputation: 3489
If you input any character other than 'y' or 'n', control enters the :
else
{
puts("invalid input");
x=0;
}
block, which resets x to 0, Now the loop condition :
while(x == 0)
is true and hence it enters the loop again.
Also you may want to skip the trailing newline character while reading like :
scanf(" %c", &choice );
Upvotes: 0
Reputation: 6899
it looping twice because enter(\n) character is stored in buffer use scanf like this(add space before %c)
scanf(" %c",&choice);
Upvotes: 2