1

Is there a way to keep this code from breaking if anything but a number is entered. Any help would be appreciated.

#include <stdio.h>

int main(){
int x;
    while(1){
        printf("Enter a number: ");
        scanf("%d", &x);
        printf("You entered %d\n", x);
    }
}
  • 4
    See [RETURN VALUE in `man scanf`](http://man7.org/linux/man-pages/man3/scanf.3.html#RETURN_VALUE). – Kenney Dec 07 '15 at 23:01
  • this is much the same as my answer to this question: http://stackoverflow.com/questions/33577920/make-loop-stop-by-pressing-dot/33578248#33578248 – bruceg Dec 07 '15 at 23:03
  • almost same as http://stackoverflow.com/questions/8817098/how-validate-user-input-when-the-expected-value-is-of-type-int-and-the-entered-v – UglyCode Dec 07 '15 at 23:03
  • 1
    `scanf("%d", &x);` is waiting - for the first input. It is just that the first non-numeric input enter is not consumed, so `scanf()` returns 0. On the next loop, that same non-numeric input is already there, Again, nothing is consumed, so `scanf()` returns 0. and again and again .... Use `fgets()` and avoid ever using `scanf()`. – chux - Reinstate Monica Dec 08 '15 at 02:29
  • `scanf` means "extract characters from `stdin`", not "wait for input" – M.M Dec 08 '15 at 03:08
  • You do realise that due to the sheer number of virtually identical questions asked on this topic, you could have found the answer to this question faster and with less keystrokes than it took you to write this question... Right? Welcome to StackOverflow. Please use the search feature before you ask questions. – autistic Dec 08 '15 at 10:07

0 Answers0