bhavi
bhavi

Reputation: 5

Taking input from user using do while loop in c

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

Upvotes: 0

Views: 1921

Answers (3)

ouille
ouille

Reputation: 56

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.

Upvotes: 0

Spikatrix
Spikatrix

Reputation: 20244

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.

Upvotes: 1

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

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);

Upvotes: 1

Related Questions