Using getchar () in a while loop prints the expression twice .. how?

I have a very simple program like this

int main()
{
    int opt;
    int n;
    int flag = 1;
    while(flag)
    {
        printf("m inside while.Press c to continue\n");
        if((opt = getchar())== 'c')
        {
            printf("choose a number\n");
            scanf(" %d",&n);
            switch(n)
            {
            case 0:
                printf("m zero\n");
                break;
            case 1:
               printf("entered one\n");
               break;
            case 3:
               printf("m exit\n");
               flag = 0;
               break;
            }
            printf("m broke\n");
        }
    }
    printf("m out\n");
    return 0;
}

I get the output as follows:

m inside while.Press c to continue
c
choose a number
1
entered one
m broke
m inside while.Press c to continue
m inside while.Press c to continue
c
choose a number

My doubt is why "m inside while.Press c to continue" is printed twice after each cycle

Thank you in advance

+4
source share
3 answers
while(flag)
{
    printf("m inside while.Press c to continue\n");
    while((opt=getchar()) != '\n') {
    if(opt == 'c')
    {
        printf("choose a number\n");
        scanf(" %d",&n);
        switch(n)
        {
        case 0:
            printf("m zero\n");
            break;
        case 1:
           printf("entered one\n");
           break;
        case 3:
           printf("m exit\n");
           flag = 0;
           break;
        }
        printf("m broke\n");
    }
    }
}
0
source

- \n, scanf. Enter, \n . scanf , nuber \n . getchar \n , , m inside while.Press c to continue , \n c.
scanf while,

while(getchar() != '\n');  

\n.
getchar .

 int main()
{
    int opt;
    int n;
    int flag = 1;
    while(flag)
    {
        printf("m inside while.Press c to continue\n");
        if((opt = getchar())== 'c')
        {
            printf("choose a number\n");
            scanf(" %d",&n);
            while(getchar() != '\n');
            switch(n)
            {
            case 0:
                printf("m zero\n");
                break;
            case 1:
               printf("entered one\n");
               break;
            case 3:
               printf("m exit\n");
               flag = 0;
               break;
            }
            printf("m broke\n");
        }
    }
    printf("m out\n");
    return 0;
}
+4

, scanf , '\n', , getchar , != 'c' :

Try the following:

        printf("choose a number\n");
        scanf(" %d",&n);
        char c;
        while (c = getchar != '\n' && c != EOF);  // clear the buffer
+2
source

All Articles