-3

I Have written a simple while program in C

// Online C compiler to run C online.
// Write C code in this online editor and run it.

#include <stdio.h>
typedef enum
{
    false = 0,
    true = 1
} bool;

int main() {
    bool res = true;
    while (res)
    {
        char choice;
        printf("Success! \n");
        printf("Do you want to continue(y/n): ");
        scanf("%c", &choice);
        if (choice == 'N' || choice == 'n')
        {
            res = false;
        }
    }
    printf("Good Bye");
}

The Program run successfully but when I type Y in Do you want to continue the loop is executed twice. How Can I Solve this?

Biraz Dahal
  • 361
  • 1
  • 5
  • 20

1 Answers1

2

Add a space before %c in scanf it skip all whitspaces(newline) like

scanf(" %c", &choice);
       ^

when I type Y in Do you want to continue the loop is executed twice ?

When you type Y+enter this will go like "Y\n" and this new line will taked by next iteration, so use above meathod to discard it.

Similiar Questions :

1)scanf() leaves the new line char in the buffer

Thanks.

srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25
  • An excerpt of and/or a link to documentation or support explaining the behavior (even be it another SO answer, which would indicate a likely duplicate) would improve this answer. – user2864740 Sep 05 '20 at 18:16
  • It answers/solves the issue. Imagine this: A programming teacher says use `" %c"` and the teacher is very clear to use a space. The teacher gives an explanation that it skips white space (as this answer does). What resource/course material support the teacher’s claim? – user2864740 Sep 05 '20 at 18:24
  • Links to others resources tend to disappear. ;-) – the busybee Sep 05 '20 at 18:30