Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am creating a program for generating next prime number, for which I need to take user input.I am using do-while loop but it doesn't stop to take input for second time. Please guide me where I am doing wrong. Thanks! This is my code snippet

int 
main()
{ 
int val=1;
char input;
do
{
    val=nextprime(val);
    printf("\n%d\t",val);

    printf("Next Prime number? Y or N ");
    scanf("%c",&input);
 } 
while(input != 'N' && input != 'n');
return 0;

}

output I am getting is :

2   Next Prime number? Y or N y

3   Next Prime number? Y or N 
5   Next Prime number? Y or N y

7   Next Prime number? Y or N 
11  Next Prime number? Y or N y

13  Next Prime number? Y or N 
17  Next Prime number? Y or N y

19  Next Prime number? Y or N 
23  Next Prime number? Y or N y

29  Next Prime number? Y or N 
31  Next Prime number? Y or N n
share|improve this question
2  
Try " %c" for your format string. See the second answer to this question. There are a ton of duplicates on this; that was the first one I ran across. –  WhozCraig Oct 3 '14 at 7:51

3 Answers 3

up vote 0 down vote accepted

You have the answer here: Reading a single character in C

When you press 'Y' you press enter, which stand in the input buffer, and is read on the next iteration of your loop.

You need to use:

scanf(" %c",&input);

With leading space to ignore last caracters in the input buffer.

share|improve this answer
    
Thanks..this really helped. –  bhavi Oct 5 '14 at 5:52

The stdin will contain y\n (y followed by a carriage return). Since your code treats any character other than N or n as yes, it calculates 2 new primes if you enter y followed by a carriage return.

To skip whitespace when reading a single char, put a space before the scan code:

scanf(" %c",&input);
share|improve this answer
    
thanks..its working now.. –  bhavi Oct 5 '14 at 5:52

Add a space before %c in the scanf will solve the issue.

This is done because scanf does not consume the \n character after you enter the first character and leaves it in the stdin.As the Enter key(\n) is also a character,it gets consumed by the next scanf call and thus,your loop gets executed once again.The space before the %c will discard all blanks like spaces.

An alternative way to overcome this would be to add getchar(); after the scanf to eat up the \n but I prefer the first one.

share|improve this answer
1  
I also prefer the first one, because it has more consistent behaviour if the user enters multiple characters at once. –  Klas Lindbäck Oct 3 '14 at 8:06
    
thanks..it worked!! –  bhavi Oct 5 '14 at 5:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.