0

I was asked to write a program that does certain task, which repeats itself if user enters 'y' or ends if user enters 'n' at the end of the task. For the sake of simplicity, let's say the task it to print "have a nice day". Here is my code:

 int main(void) {
 char cont;
 bool repeat = true;

 while (repeat == true){

 printf("Have a nice day!\n");

 printf("continue to print?\n");

 scanf("%c",&cont);

 if (cont == 'n') {repeat = false;}} 
 }

However, the output does not seem right. The actual output after entering 'y' twice and then 'n' once is

Have a nice day!
continue to print?
y
Have a nice day!
continue to print?
Have a nice day!
continue to print?
y
Have a nice day!
continue to print?
Have a nice day!
continue to print?
n

As oppose to

Have a nice day!
continue to print?
y
Have a nice day!
continue to print?
y
Have a nice day!
continue to print?
n

So basically each time 'y' is entered, the messages are printed twice istead of once. Any idea where I did wrong?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Pheegy
  • 37
  • 1
  • 7
  • 2
    Try `" %c"` for your format string (the leading space is intentional). A review of [**`scanf`**](http://en.cppreference.com/w/c/io/fscanf) may help as well. – WhozCraig Feb 27 '15 at 08:11
  • Please consider writing the condition as `if(repeat)`. Explicit comparisons against boolean literals are very redundant (the result of the comparison is, itself, just a boolean after all). Less code is often better, as long as it's clear, and `if(repeat)` is very clear, it reads well. – unwind Feb 27 '15 at 08:14
  • @Randomstudent see the linked duplicate. – WhozCraig Feb 27 '15 at 08:15
  • Change to **do{…;…;…;…}while( exitCondition ! true);** – Arif Burhan Mar 05 '16 at 21:32

1 Answers1

2
scanf("%c",&cont);

should be

scanf(" %c",&cont);

There is a newline character at the end of first input and it is being picked by the %c in next iteration. Note the space before %c which consumes the newline character

Gopi
  • 19,784
  • 4
  • 24
  • 36