0

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();

    }

`

Maroun
  • 94,125
  • 30
  • 188
  • 241
user3328692
  • 99
  • 1
  • 2
  • 8

3 Answers3

2

it looping twice because enter(\n) character is stored in buffer use scanf like this(add space before %c)

scanf(" %c",&choice);
Amit Chauhan
  • 6,151
  • 2
  • 24
  • 37
1

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
Sadique
  • 22,572
  • 7
  • 65
  • 91
0

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 );
jester
  • 3,491
  • 19
  • 30
  • it worked! But how does a simple space make the change? i am a newbie (" %c",&choice); instead of ("%c",&choice); – user3328692 Mar 13 '14 at 07:04
  • The first time you input a character and press enter, the enter remains in the buffer, only the character is consumed by the scanf. So the next time through the loop although you are entering a character, scanf consumes the first character from the input buffer which is a newline. The space before the %c in the format string instructs scanf to skip any whitespace characters till it finds the first actual character. So the newline is skipped and the actual character is read. – jester Mar 13 '14 at 07:06
  • this concept was never taught in my c book (niit). They only taught me fflush(stdin); which also worked. – user3328692 Mar 13 '14 at 07:22
  • So when i type enter does it mean \n ? – user3328692 Mar 13 '14 at 07:24
  • Enter is the newline character. fflush(stdin) also works because it flushes the input stream buffer. So if you call fflush(stdin) after the first read, the newline character in the buffer is flushed and hence it will work fine. – jester Mar 13 '14 at 07:36