...

View Full Version : DO loop orinting sentence twice instead of once in C



dannystones
10-16-2011, 03:53 PM
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

oracleguy
10-16-2011, 05:19 PM
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.)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum