tags:

views:

58

answers:

2

This is an addition drill program with a bug that I can't fix up. I can't input Y/N characters in the program, please help me to fix it up.

#include <conio.h>
#include <stdio.h>

main()
{
 int answer, count;
 int ch;
 ch = getche();

 for(count=1; count<11; count++) {
  printf("What is %d + %d? ", count, count);
  scanf("%d", &answer);
  if(answer == count + count) printf("Right!\n");
  else{
   printf("Sorry, you're wrong\n");
   printf("Would you like to try again? Y/N: \n");
   scanf("%c", &ch);

   if(ch=='Y') {
    printf("\nWhat is %d + %d? ", count, count);
    scanf("%d", &answer);
    if(answer == count+count) printf("Right!\n");
    else
     printf("Wrong, the answer is %d\n", count+count);
    }

   else
    printf("The answer is %d\n", count+count);
   }
  }
  return 0;
 }
A: 
  else{ <<<< I think this might be the issue... Everything is within this else ... maybe try to minimize nesting?
   printf("Sorry, you're wrong\n"); 
   printf("Would you like to try again? Y/N: \n"); 
   scanf("%c", &ch); 

   if(ch=='Y') { 
    printf("\nWhat is %d + %d? ", count, count); 
    scanf("%d", &answer); 
    if(answer == count+count) printf("Right!\n"); 
    else 
     printf("Wrong, the answer is %d\n", count+count); 
    } 

   else 
    printf("The answer is %d\n", count+count); 
   } <<<<< I think this might be the issue... 
Andrew
+1  A: 
scanf("%c", &ch); /* ch should be a char not an int ! */

Another problem should be scanf("%c"): there is a buffering-problem, you must clear the input buffer after that.

if I use char as data type then I get error message,that's why I used int in sted of char
Sharifhs
you use ch for getche() AND for scanf("%c"...), take one var for each function; "scanf("%c", conio.h are not C standard.