-4
#include <stdio.h>


int main()
{
    int x, y, i, temp, sum;
    char j = 'y';
    do
    {
        ...stuff...
        printf ("\nPlay again? (y\\n)\n");
        scanf("%c",&j);
    }
    while (j == 'y');
    return 0;
}

The program does the operation once and exits, without waiting to get input from user. After running once it shows "press any key to continue". How can this be fixed?

MattS
  • 1,701
  • 1
  • 14
  • 20

3 Answers3

2

This typically means that your "stuff" leaves some characters in the input stream, which that scanf successfully reads. Since the stuff in the buffer is probably not 'y', the loop terminates.

One solution would be to flush input stream before doint the scanf. See here How to clear input buffer in C?

Since in many cases the data remaining in the buffer is usually whitespace (like newline character), one simplistic solution might be to do scanf(" %c", ...) (note the extra space before %c) or even scanf("%s", ...). In both cases the pending whitespace will be skipped automatically.

Community
  • 1
  • 1
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

Use a getchar(); after the scanf()

Even if you input y and then press Enter from keyboard it also goes to the scanf("%c",&j); statement and does store a '\n' character to the variable j. So your while condition became false and thus exits the loop.

So the final program will look like this:

#include <stdio.h>

int main()
{
    int x, y, i, temp, sum;
    char j = 'y';
    do
    {
//        ...stuff...
        printf ("\nPlay again? (y\\n)\n");
        scanf("%c",&j);
        getchar(); // this will clear the ENTER you press from keyboard.
    }
    while (j == 'y');
    return 0;
}
aniskhan001
  • 7,981
  • 8
  • 36
  • 57
0

There is probably some residual input in your game loop (at least it looks like a game loop from your example) which is then being read into the j variable. This is why you are getting what appears to be a run once, no input, exit scenario.

To fix this try flushing the input stream before getting to the play again prompt. Something like:

fseek(stdin,0,SEEK_END);
Cody
  • 3,734
  • 2
  • 24
  • 29
  • 1
    Text streams (like `stdin`) do not support arbitrary absolute positioning to user-supplied numerical positions. The only legal ways to seek a text stream is to seek to the very beginning or seek to an "opaque" value returned by a previous call to `ftell`. Seeking `stdin` to `0, SEEK_END` is not allowed. – AnT stands with Russia Oct 27 '13 at 19:15