1

How could I print a message telling the input is wrong after a do-while loop? Or am I using a wrong loop?

#include <stdio.h>
#include <conio.h>

void main(){
    int inp;
    do{
        clrscr();
        printf("Enter Number < 10: ");
        scanf("%d",&inp);
    }
    while(inp>10); // Print "Wrong" when inp>10
    printf("Right Answer!");
    getch();
}
Aesthetic
  • 763
  • 1
  • 14
  • 31
  • 3
    Just add an if statement after the scanf. – this Oct 30 '13 at 05:00
  • 4
    you could add `&& printf(error)` to your while statement in order to avoid the extra check but hey... – Sinkingpoint Oct 30 '13 at 05:01
  • If you wants to validate user input..I have suggested in this answer, Read [Scanf won't execute for second time](http://stackoverflow.com/questions/17827603/scanf-wont-execute-for-second-time/17827635#17827635) – Grijesh Chauhan Oct 30 '13 at 05:08
  • 1
    And, while you're checking the inputs, don't forget to check that `scanf()` didn't report problems. You need `if (scanf("%d", &inp) != 1) { ...handle error... }` or something similar. – Jonathan Leffler Oct 30 '13 at 05:20

1 Answers1

4

You could do one of two things:

Add an extra check to the end of your while loop:

if(inp>10){
    printf("error");
}

or you can avoid the extra check, while sacrificing a bit of readability and change your while loop to

while(inp>10 && printf("error"))

This works because if the first statement if true, the printf() will not be executed due to short-circuiting, but if it is false, the printf() will be executed before the return to the top of the loop.

gpoo
  • 8,408
  • 3
  • 38
  • 53
Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45