1

I'm new to C programming, and I am having trouble with the following code.

#include <stdio.h>

int main(void)

{   
int input_number;
int largest_number = 0; 
char reply; 

printf("Hello world\n");
printf("This is a simple program, that will output the largest number entered\n");
printf("Please enter a number");
while (reply != 'N') 
{  // Start of WHILE loop


printf("Please enter a number");
scanf("%d",&input_number);
if (input_number > largest_number)
    largest_number = input_number;
printf("\nDo you wish to enter another number? Y/N\n");
scanf("%c",&reply); // Problem with this line

}  // End of WHILE loop






printf("%d",largest_number); 
getch();

The problem is this: When the user enters a number, the program outputs 'Do you wish to enter another number? Y/N'. The program does not wait for an answer though, and outputs 'Please enter a number'. The loop does stop if you enter 'N' instead of a number.

How can I get the program to wait before outputting 'Please enter a number' and exit the loop if the reply to 'Do you wish to enter another number?' is 'N'?

  • 1
    duplicate... see my [very detailed answer](http://stackoverflow.com/a/23090379/3515931). – JohnH Apr 18 '14 at 18:32
  • Note: you don't initialize the variable `reply` to any particular value. This means that before the `while` loop starts, `reply` *could* be holding `'N'` and you'd never see the loop execute. – turbulencetoo Apr 18 '14 at 18:50

1 Answers1

3

The newline character \n left behind in the buffer by first scanf is read by your scond scanf. You need to consume it. Try this

scanf(" %c",&reply);  
       ^ a space before %c can consume any number of white-spaces
haccks
  • 104,019
  • 25
  • 176
  • 264