c++scanfferror

"ferror" tests "scanf" input


I tried to enter error data in next program but it can't recognize the error. Once I entered numeric data, and next time entered string data but the program made no reaction:

#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

int main(void)
{
    int i;

    scanf("%d",&i);

    if(ferror(stdin))
        printf("Error is ocurred!");
}

Solution

  • Don't assume what a function does. Read it's documentation.

    https://www.cplusplus.com/reference/cstdio/ferror/

    int ferror ( FILE * stream );

    Check error indicator

    Checks if the error indicator associated with stream is set, returning a value different from zero if it is.

    This indicator is generally set by a previous operation on the stream that failed, and is cleared by a call to clearerr, rewind or freopen.

    So this depends on if scanf has set the error indicator, which it does not in this situation.

    Instead, use this:

    if(scanf("%d",&i) != 1) {
        // Error code
    

    Oh, and don't use use namespace std Why is "using namespace std;" considered bad practice?