c program ignores all scanfs after wrong variable type input

#include <stdio.h>
#include <stdlib.h>

int main(void) {

   int a, b, checka, checkb;

   printf ("enter a: ");
   checka = scanf ("%d", &a);

   printf ("enter b: ");
   checkb = scanf ("%d", &b);

   printf ("checka = %dn", checka);
   printf ("checkb = %d", checkb);



   return EXIT_SUCCESS;
}

I was having this problem in a larger program but I wrote a quick test to see if I could fix it, which I can't.

Basically when anything other than an integer is entered for a scanf, the program just instantly skips and ignores every other scanf and just prints the rest of the program it sees, meaning I can't make checks with a while loop, or I just get an infinite loop as the scanf in the loop to fix the variable just gets skipped.

Obviously if integers are entered this particular program will just return 1 for the last two printfs, which is expected. What am I doing wrong?

Thanks!


有一个原因,我们应该检查scanf的错误,试试这个:

#include <stdio.h>
#include <stdlib.h>

int main(void) {

    int a, b, checka, checkb;

    printf ("enter a: ");
    if((scanf ("%d", &a)) == 1){
        checka = a;
    }else{
        printf("Error(1)!");
        exit(EXIT_FAILURE);
    }


    printf ("enter b: ");
    if((scanf ("%d", &b)) == 1){
        checkb = b;
    }else{
        printf("Error(2)!");
        exit(EXIT_FAILURE);
    }

    printf ("checka = %dn", checka);
    printf ("checkb = %d", checkb);

    return EXIT_SUCCESS;
}
链接地址: http://www.djcxy.com/p/72194.html

上一篇: 我如何在'while'循环中输入整数值?

下一篇: c程序忽略错误的变量类型输入后的所有scanfs