-1

So I'm trying to make a simple calculator that allows the user to use the program again without quitting. Now the loop itself works fine, however when I use printf() it repeats it again like this and skips it:

Enter an operator: +

Do you want to continue?(Y/N): y

Enter an operator: 
Do you want to continue?(Y/N): 

Here's the code:

int main()
{
    char o, ans = 'Y';
    int num1, num2;

    while(ans == 'Y' || ans == 'y')
    {
        printf("\nEnter an operator: ");
        scanf("%c", &o);

        printf("\nDo you want to continue?(Y/N): ");
        scanf(" %c", &ans);
    }

    return 0;
}
  • 3
    It's not skipping. It's succeeding. Changing `"%c"` to `" %c"` may help you. – M.M Nov 26 '15 at 22:15
  • Possible duplicate of [C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf](http://stackoverflow.com/questions/9562218/c-multiple-scanfs-when-i-enter-in-a-value-for-one-scanf-it-skips-the-second-s) – Thomas Padron-McCarthy Nov 26 '15 at 22:27

2 Answers2

0

I'm not sure what the problem is, but you're probably not reading a char at all on the seconds scanf. You should check the return value of scanf because it tells you how many parameters have been read. Debugging this can be done using a debugger, or printing out your variables at certain points. It's the best way to learn ;)

David van rijn
  • 2,108
  • 9
  • 21
0

When you press enter, you give to your program the character '\n' and the second time your scanf has to read something it reads '\n'(the newline character). Also, it's a good idea when you want to read just a single character to use getchar(). Try modifying your code like this

while(ans == 'Y' || ans == 'y')
{
    printf("\nEnter an operator: ");
    o = getchar();
    getchar();     // because of '\n'

    printf("\nDo you want to continue?(Y/N): ");
    ans = getchar();
    getchar();    // because of '\n'
}
Da Mike
  • 447
  • 4
  • 17
  • I'll start using this, thanks. What's the between`0 = getchar()` as apposed to `ans = getchar();`? Could I just do `o = getchar();` or was it a typo? – Daniel Morris Nov 26 '15 at 22:27
  • You mean the zero instead of the letter o? That was a typo, I edited it a few seconds later. – Da Mike Nov 26 '15 at 22:30