1

I tried to use the return value of the scanf function in a for-loop

#include<stdio.h>
int main(){

int a, b, c;

for(a = 0; a < 10; ++a){
    c = scanf("%d", &b);
    if(c != 1)
        printf("error ");
    else
        printf("ok ");
}
return 0;
}

The idea is basically to prevent the user to write anything but a int value. However it went wrong, whenever the users types a none int value, it starts to loop, printing "error" over and over again until the for-loop ends. I don't want it to 'break' the for-loop when the typed value isn't a integer, but to display the "error" message and keep receiving values until the loop ends.

  • 3
    The offending non-numeric input remains in `stdin` until it is read. Add code to `if(c != 1) printf("error ");` to read that bad boy. Also watch out for a return value of `EOF`. – chux - Reinstate Monica Jun 05 '17 at 22:22
  • Something like `while ((c = getchar()) != '\n' && c != EOF) { }`. https://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c. – Stargateur Jun 05 '17 at 22:25
  • 1
    write `if(c != 1) { printf("error "); scanf("%*s"); }`; the `scanf` will consume a complete word (without the need of storing it somewhere). – Stephan Lechner Jun 05 '17 at 22:26
  • It's also a duplicate of: https://stackoverflow.com/questions/27731544/c-number-checking-funcion-gives-infinite-loop/27731696#27731696. You can see my sample code there for an answer. – GroovyDotCom Jun 05 '17 at 22:58

0 Answers0