Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Sep 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    DO loop orinting sentence twice instead of once in C

    I want the program to keep looping when i press y and end when i press n but it prints the printf() statment twice. Dont know how else to explain it really heres the code:

    #include <stdio.h>
    #include <ctype.h>
    #include <stdlib.h>
    #include <time.h>

    int main(){
    char ans;

    do{
    printf("\nDo you want to take another number?");
    scanf("%c", &ans);
    }
    while (ans!='n');
    }

    its outputting this:

    Do you want to take another number? y
    Do you want to take another number?
    Do you want to take another number? y
    Do you want to take another number?
    Do you want to take another number? y

    How do I remove the extra statements?

    Thanks
    Danny Stones

  • #2
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    I am guessing the enter key is in the buffer which is causing the duplicate statements. I would try flushing the input buffer after the scanf call. (You can google how do flush the input buffer in C.)
    OracleGuy


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •