How to fix “return value ignored: 'scanf'” code C6031 in visual studio

前端 未结 2 1206
慢半拍i
慢半拍i 2020-12-21 09:22

I am brand new to coding C (and coding in general) so I have been practicing with some random programs. This one is supposed to determine the cost of a transit ticket (Trans

相关标签:
2条回答
  • 2020-12-21 09:44

    From documentation of scanf() (e.g. https://en.cppreference.com/w/c/io/fscanf)

    Return value
    1-3) Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.

    You are ignoring that return value.

    Replace

    scanf("%d", &age);
    

    by

    int NofScannedArguments=0; /* Number of arguments which were
    successfully filled by the most recent call to scanf() */
    
    /* ...  do above once, at the start of your function */
    
    NofScannedArguments= scanf("%d", &age);
    
    /* check the return value to find out whether scanning was successful */
    if(NofScannedArguments!=1) /* should be one number */
    {
        exit(EXIT_FAILURE); /* failure, assumptions of program are not met */
    }
    

    ... to find out whether scanning succeeded. Not doing so is a bad idea and worth the warning you got.

    In case you want to handle failures more gracefully, e.g. prompt the user again,
    use a loop and read http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html about the pitfalls you may encounter.
    I am not saying you should NOT use scanf, the article explains a lot about using scanf, while trying to convince you not to.

    0 讨论(0)
  • 2020-12-21 10:10

    A bit too much here to put in a comment.

    I use a version of Visual C but it never complains about the return value from scanf not being used. What it does is to complain that scanf is unsafe and deprecated, when it isn't.

    MS thinks I should be using its own "safer" version scanf_s which is even tricker to use and IMO no safer at all – because it is not a like-for-like replacement but takes different arguments, and so it is easy to make mistakes in using it.

    One consequent problem is the compiler issues a warning for every use of scanf (and some other functions) which obscures other warnings. I deal with it as advised by adding a #define before the first library header inclusion.

    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    

    There are other matters which MS warns about too, and I actually place three #defines at the start of each file:

    #define _CRT_SECURE_NO_WARNINGS
    #define _CRT_SECURE_NO_DEPRECATE  
    #define _CRT_NONSTDC_NO_DEPRECATE
    
    #include <stdio.h>
    

    And now the relevant warnings are easy to see.

    0 讨论(0)
提交回复
热议问题