0

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
Haris
  • 12,120
  • 6
  • 43
  • 70
bhavi
  • 5
  • 2
  • 2
    Try `" %c"` for your format string. See the second answer to [**this question**](http://stackoverflow.com/questions/3744776/simple-c-scanf-does-not-work). There are a ton of duplicates on this; that was the first one I ran across. – WhozCraig Oct 03 '14 at 07:51

3 Answers3

1

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);
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
1

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.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

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.

Community
  • 1
  • 1
ouille
  • 56
  • 5